How do I compare all elements of two arrays?

anon picture anon · Feb 4, 2010 · Viewed 95.2k times · Source

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?

Answer

Amro picture Amro · Feb 4, 2010

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)