Matlab; How to compare each element of a row matrix with each element of a different row matrix?

I have two matrices in Matlab:

q = [3 4 5];  
w = [5 6 7];

I want to compare each element qwith w(i.e. 3 compared to 5, 6 and 7). If it matches any element in w(for example, how 5 is in qand w), then how qand wshare 5 as a shared key.

How can I calculate all the common keys for qand w?

+5
source share
4 answers

Try

>> x = intersect(q,w)

x = 

    5

This function treats the input vectors as sets and returns the given intersection. I think this is what you wanted to know. Is there a yes / no match? if x is empty (numel (x) == 0), there was no match.

+3
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) )
+3
[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
+2

Check out ismember, and especially the second and third output arguments if you need more information about matches.

+2
source

All Articles