How do I compare all elements of two arrays?

2019-01-07 12:36发布

问题:

I have two big arrays with about 1000 rows and 1000 columns. I need to compare each element of these arrays and store 1 in another array if the corresponding elements are equal.

I can do this with for loops but that takes a long time. How can I do this faster?

回答1:

The answers given are all correct. I just wanted to elaborate on gnovice's remark about floating-point testing.

When comparing floating-point numbers for equality, it is necessary to use a tolerance value. Two types of tolerance comparisons are commonly used: absolute tolerance and relative tolerance. (source)

An absolute tolerance comparison of a and b looks like:

|a-b| < tol

A relative tolerance comparison looks like:

|a-b| < tol*max(|a|,|b|) + tol_floor

You can implement the above two as anonymous functions:

%# absolute tolerance equality
isequalAbs = @(x,y,tol) ( abs(x-y) <= tol );

%# relative tolerance equality
isequalRel = @(x,y,tol) ( abs(x-y) <= ( tol*max(abs(x),abs(y)) + eps) );

Then you can use them as:

%# let x and y be scalars/vectors/matrices of same size
x == y
isequalAbs(x, y, 1e-6)
isequalRel(x, y, 1e-6)


回答2:

If your two matrices A and B are the same size, then you can do this:

index = A == B;

and index will be a logical array with ones everywhere an element of A and B are equal and zero otherwise.

A word of warning...

If A and B contain integers, the above should be fine. However, if they contain floating point values, you may get undesired results. The above code will only have values of one for elements that are exactly equal. Even the smallest difference will cause the elements to be considered unequal.

You can look at this question's answers for more information about dealing with the "perils of floating point operations". One solution would be to check that array elements are within a given tolerance of one another, like so:

tolerance = 0.0001;
index = abs(A-B) <= tolerance;

The above will give you a logical array index with ones everywhere the elements of A and B are within 0.0001 of each other and zero otherwise.



回答3:

Just use the normal == operator:

>> [1 2; 3 4] == [1 5; 6 4]      

ans =

     1     0
     0     1