MATLAB: Counting up starting from first row of zeros in a matrix, then 1’s.

binarycountingforfor loopifif statementmatrixrowssimplezeros

This should be relatively easy.
Given a binary matrix, i want to start counting up (starting at 1) at the first zero until the last zero. Then i want to continue counting from the top row at the first 1. Like so:
[0 1 0;1 1 0;0 0 1] becomes [1 6 2;7 8 3; 4 5 9]
Prefereably with an If and/or for statement, but im open to solutions.

Best Answer

>> a = [1,6,2;7,8,3;4,5,9] % what you want
a =
1 6 2
7 8 3
4 5 9
>> m = [0,1,0;1,1,0;0,0,1]
m =
0 1 0
1 1 0
0 0 1
Method one:
>> v = reshape(m.',1,[]);
>> [~,b] = sort(v);
>> [~,b] = sort(b);
>> b = reshape(b,size(m,2),[]).'
b =
1 6 2
7 8 3
4 5 9
Method two:
>> b = m.';
>> v = reshape(b,1,[]);
>> [~,x] = sort(v);
>> b(x) = 1:numel(m);
>> b = b.'
b =
1 6 2
7 8 3
4 5 9
Note that these will work for any number of values, not just binary matrices.