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

Matlab provides the isequal function to compare two structures for equality. However, if two structures have slightly different contents, this function does not show the differences between the two structures. To show the differences between two structures, you can use recursive function given below:

main.m
function showStructureDifferences(str1, str2)
% This function recursively compares two structures and displays their differences.
    fields_str1 = fieldnames(str1);   % field names of str1
    fields_str2 = fieldnames(str2);   % field names of str2
    common_fields = intersect(fields_str1, fields_str2);   % common field names
    % Detect removed fields
    removed_fields = find(~ismember(fields_str1, common_fields));
    for i = removed_fields
        field_name = fields_str1{i};
        if isempty(str2)
            fprintf('field "%s" is removed from the second structure\n', field_name);
        elseif isstruct(str2) && ~isfield(str2, field_name)
            fprintf('field "%s" is removed from the second structure\n', field_name);
        end
    end
    % Detect added fields
    added_fields = find(~ismember(fields_str2, common_fields));
    for i = added_fields
        field_name = fields_str2{i};
        if isempty(str1)
            fprintf('field "%s" is added in the second structure\n', field_name);
        elseif isstruct(str1) && ~isfield(str1, field_name)
            fprintf('field "%s" is added in the second structure\n', field_name);
        end
    end
    % Compare common fields
    for i = 1:length(common_fields)
        field_name = common_fields{i};
        value1 = str1.(field_name);
        value2 = str2.(field_name);
        if isstruct(value1) && isstruct(value2)
            fprintf('Comparing field "%s"\n', field_name);
            showStructureDifferences(value1, value2);  % recursive call
        else
            if ~isequal(value1, value2)
                fprintf('field "%s":\n  value 1 = %s\n  value 2 = %s\n', field_name, num2str(value1), num2str(value2));
            end
        end
    end
end
1753 chars
41 lines

You can use this function to detect differences between two big structures by calling 'showStructureDifferences(S1, S2);' where S1 and S2 are the two structures to compare. The output will show all the fields with differences.

Note: This function compares two structures recursively and can handle nested structures as well.

related categories

gistlibby LogSnag