MATLAB: Create matrix from order of numbers from binary matrix

binarymatrix

I apologize for the title gore.
Let's say I have a matrix of yes's and no's:
How do I build a new matrix from the order of the original matrix's 1's and then the 0's so it looks like the following:
If my explanation was poor. I want the new matrix to find the first "1" in the old matrix, call it 1 then find the next "1" and call it 2 and so on. After it finds all the 1's it should find all the 0's and do the same. Starting from top left and moving through the matrix like a book.

Best Answer

Caution: Untested
x = your matrix of 1's and 0's,
xt = x';
s = sum(x(:));
n = numel(x);
g = logical(xt);
xt(g) = 1:s;
xt(~g) = (s+1):n;
result = xt';