find identically variables in two different structures in matlab

To check if two structures have identical variables, you can use the following function which compares the field names and values of both structures. If they are the same, it returns true, otherwise false.

main.m
function result = compare_structs(s1, s2)
% Compares the fieldnames and values of two structures
result = isequal(struct2cell(orderfields(s1)), struct2cell(orderfields(s2)));
end
179 chars
5 lines

Example usage:

main.m
% define two structures
S1.a = 1;
S1.b = 'foo';
S2.a = 2;
S2.b = 'bar';

% compare the structures
result = compare_structs(S1, S2);
disp(result); % will return false because field values are different
201 chars
10 lines

Note that this function assumes that the fieldnames and corresponding values are of the same type and size for both structures.

related categories

gistlibby LogSnag