recipes : programming : Are two matrices identical?

Problem

How do I check if two matrices are identical?

Solution

There's a bunch of ways you can do this depending on what exactly it is you want to test. Let's say you only care whether the matrices are the same size (the same number of dimensions and the dimensions having the same lengths):

A=randn([3,4,10]); %A 3 by 4 by 10 3-D matrix
B=randn([3,4,10]); %Another  3 by 4 by 10 3-D matrix

%To test if they have the same number of dimensions we do:
ndims(A)==ndims(B)


%To test if the dimensions are all of equal sizes we do:
all(size(A)==size(B))

The above lines both return 1 if they are true and 0 if they are false. The all command returns 1 (true) if all elements of a vector are non-zero. So if one pair of dimensions in A and B were not equal, the all command would return 0 (false). Of course it makes most sense to turn those lines of code into a stand-alone function. Here's one way of doing that: compSize.m. Try feeding the matrices A and B into that function. Try also with matrices that are not equal in size.

Maybe what you care about isn't whether two matrices are the same size but whether their contents are identical. Here's how to check that.

A=ones([3,4,10]); %A 3 by 4 by 10 3-D matrix
B=ones([3,4,10]); %Another  3 by 4 by 10 3-D matrix

%The "roll your own" solution:
~any(A(:)-B(:)) %returns 1 if all element-wise subtractions were zero

%The built-in solution:
isequal(A,B) %Returns 1 if the contents of the matrices are equal

The roll your own solution is nice, because it gives you a feeling for how stuff like this can work. However, it's about ten times slower than isqual and isequal will test more than one pair of matrices. So the second is the better solution.

Discussion

How come the built-in isqual function is so much faster than what we typed into the command-line? Surely that line of code was very simple! Try typing edit isqual, to see the contents of the m-file. You will find that contains only comments and no code lines. The reason for this is that isequal.m is actually calling compiled code located elsewhere. So the built-in function has been well optimised and beats the code you type at the command line.