This will do it:
A(A ~= 0) = 1:nnz(A)
Pregunta
Good morning/afternoon~
I have an array like this,
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]
the output should be:
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]
What should I do to replace the non-zero elements in A with sequential number?
Solución
This will do it:
A(A ~= 0) = 1:nnz(A)
Otros consejos
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)
B = cumsum(A ~= 0) .* (A ~= 0);