MATLAB: Number consecutively a matrix row-wise

MATLABmatrixnannumer consecutivelyrow-wise

Hi guys,
I'm trying to number consecutively all elements in a matrix, which are not NaN. It is important that it should be row-wise.
Example:
M=NaN(5,7); M(1,3:5)=1; M(2,3:6)=2; M(3,1:4)=23; M(4,5:7)=75
M = NaN NaN 1 1 1 NaN NaN
NaN NaN 2 2 2 2 NaN
23 23 23 23 NaN NaN NaN
NaN NaN NaN NaN 75 75 75
NaN NaN NaN NaN NaN NaN NaN
For my task, I need to have it like that:
M = NaN NaN 1 2 3 NaN NaN
NaN NaN 4 5 6 7 NaN
8 9 10 11 NaN NaN NaN
NaN NaN NaN NaN 12 13 14
NaN NaN NaN NaN NaN NaN NaN
I have tried it unseccessfully with some nested for and if loops. I only numbered all columns or all rows the with the same number. As far as I know, 'find()' always searches column-wise, am I right there?
Would be great if some of you have some ideas.

Best Answer

>> M=NaN(5,7); M(1,3:5)=1; M(2,3:6)=2; M(3,1:4)=23; M(4,5:7)=75;
Method one: find and sub2ind:
>> [C,R] = find(~isnan(M.'));
>> M(sub2ind(size(M),R,C)) = 1:numel(C)
M =
NaN NaN 1 2 3 NaN NaN
NaN NaN 4 5 6 7 NaN
8 9 10 11 NaN NaN NaN
NaN NaN NaN NaN 12 13 14
NaN NaN NaN NaN NaN NaN NaN
Method two: transpose:
>> M = M.';
>> X = ~isnan(M(:));
>> M(X) = 1:nnz(X);
>> M = M.'
M =
NaN NaN 1 2 3 NaN NaN
NaN NaN 4 5 6 7 NaN
8 9 10 11 NaN NaN NaN
NaN NaN NaN NaN 12 13 14
NaN NaN NaN NaN NaN NaN NaN