Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octave/MATLAB: How to compare structs for equality?

Tags:

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
like image 251
Andrew Tomazos Avatar asked Mar 31 '12 00:03

Andrew Tomazos


People also ask

How do you know if structs are equal?

To find out if they are the same object, compare pointers to the two structs for equality. If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.

Can we compare 2 structure variables directly?

yes,we can compare by using thir addresses. If the 2 structures variable are initialied with calloc or they are set with 0 by memset so you can compare your 2 structures with memcmp. It is possible to use memcmp if: 1) the structs contain no floating-point fields.

How do you compare two arrays are equal in Matlab?

tf = isequal( A,B ) returns logical 1 ( true ) if A and B are equivalent; otherwise, it returns logical 0 ( false ). See the Input Arguments section for a definition of equivalence for each data type.


2 Answers

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)
like image 145
Pursuit Avatar answered Sep 22 '22 03:09

Pursuit


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.

like image 20
ely Avatar answered Sep 25 '22 03:09

ely