How to find multiple numbers in a matrix

조회 수: 8(최근 30일)
Hi everyone,
Please show me how to find multiple numbers in a matrix. Lets say I have a matrix:
A = [1 2 3 3 5 6; 7 8 3 3 5 12; 13 14 3 3 17 5];
So I want to find number 3 in the matrix. I used this code:
for i=1:3;
for j=1:length(A);
if A (i,j) == 3;
b (i,j) = 1;
else
b (i,j) = 0;
end
end
end
Then I got:
b = [0 0 1 1 0 0; 0 0 1 1 0 0; 0 0 1 1 0 0]
But my problem is how if I want to find position of 2 numbers in a matrix, for example 3 and 5. I want the answer look like this:
b = [0 0 1 1 1 0; 0 0 1 1 1 0; 0 0 1 1 0 1]

채택된 답변

Stephen23
Stephen23 2018년 4월 2일
편집: Stephen23 2018년 4월 2일
The most generalized solution is to use ismember:
>> A = [1,2,3,3,5,6;7,8,3,3,5,12;13,14,3,3,17,5];
>> b = ismember(A,[3,5])
This trivially adjusts to any size of A, or any number of values that you want to match.
  댓글 수: 1
Kasmayanti Sakaria
Kasmayanti Sakaria 2018년 4월 2일
Thank you. It works :)

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

추가 답변(2개)

Abhishek Ballaney
Abhishek Ballaney 2018년 4월 2일
https://in.mathworks.com/help/matlab/ref/find.html

David Fletcher
David Fletcher 2018년 4월 2일
편집: David Fletcher 2018년 4월 2일
A = [1 2 3 3 5 6; 7 8 3 3 5 12; 13 14 3 3 17 5];
b=A==3 | A==5
  댓글 수: 1
Kasmayanti Sakaria
Kasmayanti Sakaria 2018년 4월 2일
Thanks. This also works.

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by