Matlab, How do I compare each element of a row matrix with each element of another row matrix?
I have two matrices in Matlab:
开发者_Python百科q = [3 4 5];
w = [5 6 7];
I want to compare every element of q
with w
(i.e. 3 compared with 5, 6, and 7). If it matches any element in w
(like how 5 is in both q
and w
) then both q
and w
share 5 as a common key.
How can I compute all the common keys for q
and w
?
Try
>> x = intersect(q,w)
x =
5
This function treats the input vectors as sets and returns the set intersection. I think this is what you wanted to know. Is there a match yes/no? if x is empty (numel(x)==0) there was no match.
q = [3 4 5];
w = [5 6 7];
%# @sellibitze
intersect(q,w)
%# @Loren
q( ismember(q,w) )
%# Me :)
q( any(bsxfun(@eq, q, w'),1) )
[Q W] = meshgrid(q, w)
% Q =
% 3 4 5
% 3 4 5
% 3 4 5
% W =
% 5 5 5
% 6 6 6
% 7 7 7
Q == W
% ans =
% 0 0 1
% 0 0 0
% 0 0 0
Check out ismember, and especially the second and third output argumements if you need more information about the matches.
精彩评论