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)