20

How do I compare two structs for equality in octave (or matlab)?

Attempting to use the == operator yields:

binary operator `==' not implemented for `scalar struct' by `scalar struct' operations
Andrew Tomazos
  • 66,139
  • 40
  • 186
  • 319

2 Answers2

24

Use either the isequal or isequalwithequalnans function. Example code:

s1.field1 = [1 2 3];
s1.field2 = {2,3,4,{5,6}};
s2 = s1;
isequal(s1,s2)  %Returns true (structures match)

s1.field3 = [1 2 nan];
s2.field3 = [1 2 nan];
isequal(s1, s2)              %Returns false (NaN ~= NaN)
isequalwithequalnans(s1, s2) %Returns true  (NaN == NaN)

s2.field2{end+1}=7;
isequal(s1,s2)               %Returns false (different structures)

isequal(s1, 'Some string')   %Returns false (different classes)
Pursuit
  • 12,285
  • 1
  • 25
  • 41
  • 5
    @user1131467: If the structs contain `NaN`, `isequal` may return `false` even though we would consider the structs similar. Thus, I suggest using `isequalwithequalnans` instead of `isequal`. – Jonas Mar 31 '12 at 06:28
  • 4
    In R2012b use [`isequaln`](http://www.mathworks.com/help/matlab/ref/isequaln.html). – b3. Sep 20 '12 at 16:54
2

I would just write a function isStructEqual(struct1,struct2) that performs regular comparisons on all of the member attributes. If any such comparison returns 'false' or '0', then immediately exit and return 'false', otherwise if it makes it all the way through the list of member attributes without that happening, return true. If the struct is extremely large, there are ways to automate the process of iterating over the member fields.

Looking on the central file exchange, you might try this file.

ely
  • 74,674
  • 34
  • 147
  • 228
  • Is there any reason this isn't implemented as part of the language or standard library? It would seem like fairly basic functionality. – Andrew Tomazos Mar 31 '12 at 00:22
  • Probably just because they don't want to support a complicated comparison for various struct variables. I'm not sure what all can be a member attribute, but what if things like symbolic variables, or tool-box specific objects are added as struct fields. If someone else doesn't have the right toolbox, it might cause problems, and that might just be a low-priority headache for the Mathworks folks. I'm not a big fan of Mathworks because of things like that. If you have the option to work in another language and want to, consider Python with NumPy. – ely Mar 31 '12 at 00:39
  • 1
    Octave mandated by course unfortunately. If I had my way I'd use C++, stl, maybe boost and a sci math library like Armadillo: http://arma.sourceforge.net/ – Andrew Tomazos Mar 31 '12 at 01:30
  • +1 for the FE link. I just recently had to write a similar function. – yuk Mar 31 '12 at 02:43