user2491492
user2491492

Reputation: 21

how to cumulatively number zero entries in matrix in matlab

I have a matrix Composed of zero and one entries as follows

1 0 0 1
1 0 0 1
0 0 0 0

And i need to replace the entries with Numbers as follows

First zero should be 1, second should Be 2...nth zero to be n

Then the first one should Be n+1, second one should Be n+2...i'th one to Be n+i

Resulting in The Following matrix

9  2  5  11
10 3  6  12
1  4  7  8

This should work for any 3xn matrix with zero and one entries anywhere.

Thanks

Upvotes: 2

Views: 44

Answers (2)

Eitan T
Eitan T

Reputation: 32920

Use logical indexing:

idx = ~A(:); %// Indices of zeros
A(idx) = 1:nnz(idx);
A(~idx) = nnz(idx) + 1:numel(A);

Upvotes: 1

John
John

Reputation: 5905

Here are the steps you need to take, to get the 0 part done. Rinse and repeat to get other numbers. The 0's in "result" are the locations that need to get updated.

>> a
a =
     1     0     0     1
     1     0     0     1
     0     0     0     0
>> ix = find(a==0);
>> result = zeros(size(a));
>> result(ix) = 1 : numel(ix)
result =
     0     2     5     0
     0     3     6     0
     1     4     7     8

Upvotes: 0

Related Questions