check if two structures have the same content if not show me the differences in matlab

To check if two structures have the same content, you can use the isequal function in Matlab. Example code to compare two structures would be:

main.m
struct1.a = 1;
struct1.b = 2;
struct1.c = 3;

struct2.a = 1;
struct2.b = 2;
struct2.c = 4;

if isequal(struct1, struct2)
    disp('The structures have the same content');
else
    disp('The structures do not have the same content');
    fields1 = fieldnames(struct1);
    fields2 = fieldnames(struct2);
    for i = 1:length(fields1)
        field = fields1{i};
        if ~isequal(struct1.(field), struct2.(field))
            fprintf('%s is different: struct1.%s = %d, struct2.%s = %d\n', field, field, struct1.(field), field, struct2.(field));
        end
    end
end
570 chars
22 lines

This code will output:

main.m
The structures do not have the same content
c is different: struct1.c = 3, struct2.c = 4
89 chars
3 lines

This indicates that the two structures are not equal, and shows where the differences are in the structure content by comparing struct1 and struct2 field-by-field.

related categories

gistlibby LogSnag