1

早安/午安~

我有一个这样的数组,

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 中的非零元素?

4

4 回答 4

5

这将做到:

A(A ~= 0) = 1:nnz(A)
于 2013-04-16T16:56:07.667 回答
0
B = cumsum(A ~= 0) .* (A ~= 0);
于 2013-04-16T17:32:06.693 回答
0
A(ismember(A,A(A(:) ~=0))) = 1:numel(A(A(:) ~=0))
于 2013-04-16T17:00:24.073 回答
0

With the image processing toolbox (will give the same label to adjacent non-zero values, though):

B = bwlabel(A)
于 2013-04-16T17:25:08.043 回答