MATLAB: Matrix and find

findmatrixmatrix manipulation

Hello actually i have a random matrix done of a lot of 0 and some 1. i need to save the position (i,j) of the first 1 for each row/column. If i have a matrix like this one
0 1 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 1 0 0 0 0 0
doing a(i)=find(matrix(i,:),1) i got a=[2,3,3], and this is ok.
Instead if i have this matrix:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
doing the same thing with the find i got error.
Improper assignment with rectangular empty matrix.
why?

Best Answer

You have to decide, what you want as output, if a row does not contain any 1.
n = size(matrix, 1);
a = zeros(1, n); % Pre-allocate!

for i = 1:n
found = find(matrix(i,:), 1);
if isempty(found)
a(i) = NaN; % Or Inf, or -1, or 0, or whatever?!
else
a(i) = found;
end
end
[EDITED]: You can define the default value in the pre-allocation to make the code 2 lines shorter:
n = size(matrix, 1);
a = nan(1, n); % Pre-allocate!
for i = 1:n
found = find(matrix(i,:), 1);
if ~isempty(found)
a(i) = found;
end
end
Related Question