MATLAB Answers

How to find multiple numbers in a matrix

21 views (last 30 days)
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]

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 2 Apr 2018
Edited: Stephen Cobeldick on 2 Apr 2018
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 Comment

Sign in to comment.

More Answers (2)

Abhishek Ballaney
Abhishek Ballaney on 2 Apr 2018
https://in.mathworks.com/help/matlab/ref/find.html

  1 Comment

Sign in to comment.


David Fletcher
David Fletcher on 2 Apr 2018
Edited: David Fletcher on 2 Apr 2018
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 Comment

Sign in to comment.

Sign in to answer this question.

Tags

Products