14

Possible Duplicate:
Octave/MATLAB: How to compare structs for equality?

is there a simple comparison function for matlab cell or struct objects? using '==' doesn't seem to work :(

Community
  • 1
  • 1
urso
  • 924
  • 1
  • 7
  • 17
  • This question has been marked as a duplicate; however, this question is older then the one being compared to. The newer question should be marked as the duplicate. – b3. Mar 05 '15 at 03:26

2 Answers2

8

If you want to know if two cell arrays or struct objects are exactly equal you could always use isequaln.

b3.
  • 7,094
  • 2
  • 33
  • 48
  • 1
    This will not work if any of the structure fields contains a NaN. You can also not call isnan for a struct to know if there is a problem in the first place. This makes it a rather unreliable general purpose comparison method. – angainor Sep 19 '12 at 08:42
  • Actually, you should use isequalwithequalnans for this. See [this SO post](http://stackoverflow.com/questions/9951828/octave-matlab-how-to-compare-structs-for-equality). – angainor Sep 19 '12 at 08:51
  • 1
    In R2012b there is now the more concisely named [isequaln](http://www.mathworks.com/help/matlab/ref/isequaln.html) function. – b3. Sep 20 '12 at 16:52
6

Use isequal to compare two cells. Note however that == is not advised even for arrays:

>> A = [1 2 3 4 5];
>> B = [1 2 3 4 5];
>> A == B
ans =

     1     1     1     1     1

You would need to use a further trick to use that expression in a if statement for instance.

The reason == is not recommended for variables of type double is because of the IEEE 754 representation use by MATLAB. For instance:

  >> .1 + .1 + .1 == .3

  ans =

       0

To compare double values more robustly, you can use the abs function in MATLAB:

>> if ( abs( (.1+.1+.1) - .3 ) < 1e-10 ); disp('Values are pretty close although not necessarily bit equal'); end
Values are pretty close although not necessarily bit equal
>> 
Community
  • 1
  • 1
Greg
  • 6,038
  • 4
  • 22
  • 37