Octave/MATLAB: How to compare structs for equality?

杀马特。学长 韩版系。学妹 提交于 2019-11-28 10:47:15

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)

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!