Suzan Cioc
Suzan Cioc

Reputation: 30097

How to compare multidimensional arrays in Matlab?

Suppose A and B are multidimensional arrays. The number and size of dimensions are unknown apriori.

How to compare both the number of dimensions and corresponding elements to ensure they are equal (or close for double values)?

Upvotes: 3

Views: 1358

Answers (3)

chipaudette
chipaudette

Reputation: 1675

To compare the sizes, you can compare the output of the size function. Then, once you know the sizes are the same, you can compare the matrices directly...by first turning them into a 1-D vector so that you only need one all command. Something like

if (ndims(A) == ndims(B))
    disp('They have the same number of dimensions!');    
    if all(size(A) == size(B))
        disp('They are the same size!']);
        if all(A(:) == B(:))
            disp(['They hold the same values!']);
        end
    end
end

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

For strict equality of values (and of course of dimensions), use isequal:

isequal(A,B) returns logical 1 (true) if A and B are the same size and their contents are of equal value; otherwise, it returns logical 0 (false).

Example:

>> A = [1 2; 3 4];
>> B = [10 20 30];
>> equal = isequal(A,B)
equal =
     0

Equivalently, you can evaluate the three conditions:

  1. same number of dimensions,
  2. same size along each dimension, and
  3. same values for all entries

with short-circuit "and", so that each condition is only evaluated if the preceding one is met:

equal = ndims(A)==ndims(B) && all(size(A)==size(B)) && all(A(:)==B(:));

This allows generalizing the last condition to test for close enough values:

tol = 1e-6;
equal = ndims(A)==ndims(B) && all(size(A)==size(B)) && all(abs(A(:)-B(:))<tol);

Upvotes: 5

adalca
adalca

Reputation: 145

I would compare the dimensions first:

assert(ndims(A) == ndims(B), 'Dimensions are not the same');

then the sizes

assert(all(size(A) == size(B)), 'Sizes are not the same');

and then compare the elements

assert(all(A(:) == B(:)), 'Some elements are not the same'); 

If you're looking to compare for "closeness", then you could do

assert(all(abs(A(:) - B(:)) < thr), 'Some elements are not close');  

for some threshold thr of closeness.

Upvotes: 2

Related Questions