Matrix and find

조회 수: 2 (최근 30일)
Salvatore Turino
Salvatore Turino 2012년 1월 15일
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?
  댓글 수: 1
Image Analyst
Image Analyst 2012년 1월 15일
What do you want or expect to get when you have no 1's in the row? Maybe -1 or something? It's got to be something.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2012년 1월 15일
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
  댓글 수: 1
Salvatore Turino
Salvatore Turino 2012년 1월 16일
thank you :) this is was i was looking for. yesterday evening i did it in a different way but your code is more compact and functional. thank you

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

the cyclist
the cyclist 2012년 1월 15일
For the first matrix, when i=1, "find(matrix(1,:),1)" looks at the first row of the matrix, and looks for the first column that has a non-zero in it. That's column 2, so you are doing a(1)=2, which is fine.
For the second matrix, when i=1, the same command returns the empty matrix, because there is no non-zero in the first row. Therefore, you are trying to do a(1)=[], which gives the error you see.
Edit in response to your comment:
Here's a different way from Jan's, in which only the rows that actually have non-zeros are displayed:
x = [0 1 0 0 0 1 0 0 ...
0 0 1 0 0 0 0 0 ...
0 0 1 0 0 0 0 0];
[m,n]=find(x);
[rowsWithNonZero,indexToFindColumn] = unique(m,'first');
columnsOfFirstNonZero = n(indexToFindColumn);
disp('row:')
disp(rowsWithNonZero)
disp('column:')
disp(columnsOfFirstNonZero)

Salvatore Turino
Salvatore Turino 2012년 1월 15일
ok and a possible solution?i need something that find me all the first 1 of the matrix in both cases

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by