user2269065
user2269065

Reputation: 35

Assign sequential number to integer element in array

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?

Upvotes: 1

Views: 153

Answers (4)

Serg
Serg

Reputation: 14098

B = cumsum(A ~= 0) .* (A ~= 0);

Upvotes: 0

Jonas
Jonas

Reputation: 74930

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

B = bwlabel(A)

Upvotes: 0

fpe
fpe

Reputation: 2750

A(ismember(A,A(A(:) ~=0))) = 1:numel(A(A(:) ~=0))

Upvotes: 0

Bjoern H
Bjoern H

Reputation: 600

This will do it:

A(A ~= 0) = 1:nnz(A)

Upvotes: 5

Related Questions