Star
Star

Reputation: 2299

Compare row-wise two matrices in Matlab

I have two matrices to compare in Matlab, A of dimension MxN and C of dimension MxN. I want to get an index equal to 1 if there is i such that A(i,:) differs from C(i,:) and 0 otherwise.

For example

A=[1 2 3; 4 5 6; 7 8 9];
C=[1 2 3; 4 5 6; 10 11 12];
index=1;

I want the fastest code possible.

Also, can you provide a second version of the code, if different from earlier, for the case in which

(1) A contains only zeros and ones and C=zeros(M,N), and

(2) A contains only zeros and ones and C=ones(M,N).

Upvotes: 0

Views: 203

Answers (1)

Suever
Suever

Reputation: 65470

You can use isequal to perform an element-wise equality and then negate it with ~ to see if there were any cases where A and C differed.

index = ~isequal(A, C)

If A and C are floating point numbers, then you'll want to not use exact equality checks and use something like

index = ~any(abs(A(:) - C(:)) < eps);

As for the second part of your question, you'll have to add an additional conditional

index = ~isequal(A, C) || ...
        (all(ismember(A(:), [0 1])) && (all(C(:) == 0) || all(C(:) == 1)));

Upvotes: 3

Related Questions