MATLAB: How to find all matrix elements that equals any value from a certain list without looping over the list elements

arraysfindloopsMATLAB

Hi all,
I'm trying to find all matrix elements that equals any value from a certain list without looping over the list elements. I've read the manuel about it here but it seems to not suit my needs.
Let say I have:
A = [1,2,3;
4,5,6;
7,8,9];
valuesVec = [1,5,8];
And I want to get the logical matrix that indicates where are all the values in 'valuesVec' are.
Basically I want to do something like this:
resultMat = A == values;
And expecting to get (for this example)
resultMat = [1,0,0;
0,1,0;
0,1,0];
I'll point out that some numbers can repeat themselfs and I want to get all of them, i.e. if I have this:
A = [1,2,1;
8,5,6;
7,8,5];
valuesVec = [1,5,8];
I'll get:
resultMat = [1,0,1;
1,1,0;
0,1,1];
I know I can do it by 'for looping' over all the values in valuesVec… But I'm looking for some more elegant (and faster) way of doing it.
Thanks a lot!
Barak.

Best Answer

Wanted = A == valuesVec(:)
%or
Wanted = bsxfun(@eq, A, valuesVec(:)) % for versions <= 2016a
% or For your last example
Wanted = ismember(A,valuesVec)