Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 776
Suzan Cioc Avatar asked Dec 29 '25 08:12

Suzan Cioc


1 Answers

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);
like image 83
Luis Mendo Avatar answered Dec 31 '25 22:12

Luis Mendo