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?
Just use the normal
==
operator:If your two matrices
A
andB
are the same size, then you can do this:and
index
will be a logical array with ones everywhere an element ofA
andB
are equal and zero otherwise.A word of warning...
If
A
andB
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:
The above will give you a logical array
index
with ones everywhere the elements ofA
andB
are within 0.0001 of each other and zero otherwise.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
andb
looks like:A relative tolerance comparison looks like:
You can implement the above two as anonymous functions:
Then you can use them as: