对比两个结构体那些 field 中的值发生了改变,可以找到结构体之间的不同。

function diff = CompareStruct(s1, s2)
    fields1 = fieldnames(s1);
    fields2 = fieldnames(s2);
    filsame = isequal(fields1,fields2); 
    if(~filsame)
        disp('结构体属性不一致')
        diff=setxor(fields1,fields2) ;
    else
        diff = struct();
        for i = 1:numel(fields1)
            field = fields1{i};
            if ~isequal(s1.(field), s2.(field))
                diff.(field) = {s1.(field), s2.(field)};
            end
        end
    end
end

实现的效果:

clear all;
clc;

s1.field1 = 'value1';
s1.field2 = 123;
s1.field3 = [1 2 3];

s2.field1 = 'value1';
s2.field2 = 456;
s2.field3 = [4 5 6];

diff = CompareStruct(s1,s2)

输出
函数返回两个结构体之间不同的 field 以及对应的值。