Find rows in matrix based on columns value
이전 댓글 표시
If i have a matrix:
mat = [1 2 3 4;
5 6 7 8;
9 10 11 12];
How do i find the row index where the column has value 10 and 11 for example? In this case, the row index will be 3 since it has columns with 10 and 11.
I tried doing something like:
find(mat(:,2) == 10 && mat(:,3) == 11)
But it doesn't work.
댓글 수: 1
Andrei Bobrov
2019년 9월 2일
find(mat(:,2) == 10 & mat(:,3) == 11)
채택된 답변
추가 답변 (2개)
madhan ravi
2019년 9월 2일
편집: madhan ravi
2019년 9월 2일
ix = sum(ismember(mat,[10,11]),2)==2;
row_index = find(ix)
edit:
row_index = find(sum(~mod(mod(mat,10),11),2)==1)
댓글 수: 3
Andrei Bobrov
2019년 9월 2일
Hi Madhan!
Your result for follow case:
mat = [10 2 3 8
5 7 10 3
9 10 11 11];
>> row_index = find(sum(~mod(mod(mat,10),11),2)==1)
row_index =
1
2
3
>>
madhan ravi
2019년 9월 2일
편집: madhan ravi
2019년 9월 2일
Yes Andrei, I realised just before your comment :). Hi Andrei, how about:
m=any(~mod(mat,10),2) & any(~mod(mat,11),2);
w=find(m)
Andrei Bobrov
2019년 9월 2일
All right! +1.
Andrei Bobrov
2019년 9월 2일
편집: Andrei Bobrov
2019년 9월 2일
My case for mat:
mat = [1 11 3 10
5 6 10 10
9 10 11 12];
mat2 = sort(mat,2);
[m,n] = size(mat);
mat3 = mat2([(1:end-m)',(m+1:end)']);
iii = mod((1:m*n-m)'-1,m)+1;
out = sort(iii(ismember(mat3,[10,11],'rows')));
or
[i1,~] = find(mat == 10);
[i2,~] = find(mat == 11);
out = intersect(i1,i2);
another variant:
out = all(any(mat == reshape([10,11],1,1,[]),2),3);
댓글 수: 6
Andrei Bobrov
2019년 9월 2일
편집: Andrei Bobrov
2019년 9월 2일
for my case:
mat = [1 11 3 10
5 6 10 10
9 10 11 12];
Madhan's result:
>> ix = sum(ismember(mat,[10,11]),2)==2;
row_index = find(ix)
row_index =
1
2
3
>>
madhan ravi
2019년 9월 2일
편집: madhan ravi
2019년 9월 2일
Ah thanks Andrei, +1
Robert U
2019년 9월 2일
The description of the cited solution says "If you want to find the values 10 OR 11 within the matrix, and return the rows they have been found in, [...]". That is what it does.
Robert U
2019년 9월 2일
What Steward Tan might want is to find rows containing 10 AND 11 within the matrix, but he did not describe it as that.
row = find(arrayfun(@(ind) any(mat(ind,:) == 10) & any(mat(ind,:) == 11),1:size(mat,1)));
Kind regards,
Robert
Andrei Bobrov
2019년 9월 2일
I'm sorry Robert, my mistake!
Stewart Tan
2019년 9월 2일
카테고리
도움말 센터 및 File Exchange에서 Programmatic Model Editing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!