tags:

views:

76

answers:

3

hi,

I need to compare the content of 2 tables, more exactly 2 columns (1 column per table) in Matlab to see, for each element of the firsts column, there is an equal element in the second column.

Should I use a for loop or is there any MATLAB function doing this ?

thanks

+1  A: 

did you know you could do this:

>> a = [1:5];
>> b = [5:-1:1];
>> a == b

ans =

     0     0     1     0     0

so you could compare 2 columns in matlab by using the == operator on the whole column. And you could use the result from that as a index specifier to get the equal values. Like this:

>> a(a == b)

ans =

     3

This mean, select all the elements out of a for which a == b is true.

For example you could also select all the elements out of a which are larger than 3:

>> a(a > 3)

ans =

     4     5

Using this knowledge I would say you could solve your problem.

Davy Landman
+2  A: 

If the order is important, you do element-wise comparison, after which you use all

%# create two arrays
A = [1,2;1,3;2,5;3,3];
B = [2,2;1,3;1,5;3,3];

%# compare the second column of A and B, and check if the comparison is `true` for all elements
all(A(:,2)==B(:,2))
ans = 
    1

If the order is unimportant and all elements are unique, use ismember

all(ismember(A(:,1),B(:,1))
ans = 
    1

If the order is unimportant, and there are repetitions, use sort

all(sort(A(:,1))==sort(B(:,2)))
ans = 
    0
Jonas
A: 

For arithmetic values, both solutions mentioned will work. For strings or cell arrays of strings, use strcmp/strcmpi.

From the help file:

TF = strcmp(C1, C2) compares each element of C1 to the same element in C2, where C1 and C2 are equal-size cell arrays of strings. Input C1 or C2 can also be a character array with the right number of rows. The function returns TF, a logical array that is the same size as C1 and C2, and contains logical 1 (true) for those elements of C1 and C2 that are a match, and logical 0 (false) for those elements that are not.

An example (also from the help file):

Example 2

Create 3 cell arrays of strings:

A = {'MATLAB','SIMULINK';'Toolboxes','The MathWorks'};
B = {'Handle Graphics','Real Time Workshop';'Toolboxes','The MathWorks'};
C = {'handle graphics','Signal Processing';'  Toolboxes', 'The MATHWORKS'};

Compare cell arrays A and B with sensitivity to case:

strcmp(A, B)
ans =
     0     0
     1     1

Compare cell arrays B and C without sensitivity to case. Note that 'Toolboxes' doesn't match because of the leading space characters in C{2,1} that do not appear in B{2,1}:

strcmpi(B, C)
ans =
     1     0
     0     1

To get a single return value rather than an array of logical values, use the all function as explained by Jonas.

JS Ng

related questions