早安/午安~
我有一个这样的数组,
A= [12 0 0 0 0 3 0 0 0 66 0 0 0 0 20 0 0 2 0 31 0 0 42 0 32 0 38]
输出应该是:
B= [ 1 0 0 0 0 2 0 0 0 3 0 0 0 0 4 0 0 5 0 6 0 0 7 0 8 0 9]
我应该怎么做才能用序号替换 A 中的非零元素?
早安/午安~
我有一个这样的数组,
A= [12 0 0 0 0 3 0 0 0 66 0 0 0 0 20 0 0 2 0 31 0 0 42 0 32 0 38]
输出应该是:
B= [ 1 0 0 0 0 2 0 0 0 3 0 0 0 0 4 0 0 5 0 6 0 0 7 0 8 0 9]
我应该怎么做才能用序号替换 A 中的非零元素?
这将做到:
A(A ~= 0) = 1:nnz(A)
B = cumsum(A ~= 0) .* (A ~= 0);
A(ismember(A,A(A(:) ~=0))) = 1:numel(A(A(:) ~=0))
With the image processing toolbox (will give the same label to adjacent non-zero values, though):
B = bwlabel(A)