Octave/MATLAB: How to compare structs for equality?

Andrew Tomazos picture Andrew Tomazos · Mar 31, 2012 · Viewed 8.2k times · Source

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

Answer

Pursuit picture Pursuit · Mar 31, 2012

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)