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)?
For strict equality of values (and of course of dimensions), use isequal:
isequal(A,B)returns logical1(true) ifAandBare the same size and their contents are of equal value; otherwise, it returns logical0(false).
Example:
>> A = [1 2; 3 4];
>> B = [10 20 30];
>> equal = isequal(A,B)
equal =
0
Equivalently, you can evaluate the three conditions:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With