find the difference between two structures without structdiff in matlab

To find the difference between two structures without using the built-in function structdiff in Matlab, you can implement a custom function that iterates over each field of both structures and compares their values.

Here's an example implementation:

main.m
function diff = struct_diff(struct1, struct2)
    % Get the fields of both structures
    fields1 = fieldnames(struct1);
    fields2 = fieldnames(struct2);
    
    % Find the fields that are in one structure but not the other
    only_in_struct1 = setdiff(fields1, fields2);
    only_in_struct2 = setdiff(fields2, fields1);
    
    % Initialize the output structure
    diff = struct();
    
    % Iterate over the fields that are in both structures
    for i = 1:length(fields1)
        % Get the field name
        field_name = fields1{i};
        
        % Get the value of the field in both structures
        value1 = struct1.(field_name);
        value2 = struct2.(field_name);
        
        % Compare the values and add to the output structure if they are different
        if ~isequal(value1, value2)
            diff.(field_name) = {value1, value2};
        end
    end
    
    % Add the fields that are only in one structure to the output structure
    for i = 1:length(only_in_struct1)
        field_name = only_in_struct1{i};
        diff.(field_name) = {struct1.(field_name), []};
    end
    for i = 1:length(only_in_struct2)
        field_name = only_in_struct2{i};
        diff.(field_name) = {[], struct2.(field_name)};
    end
end
1256 chars
38 lines

This function takes two structures as input and returns a structure containing the differences between them. The output structure has the same field names as the input structures, and each field contains a cell array with two values: the value of the field in the first structure and the value of the field in the second structure. If a field exists in one structure but not the other, the corresponding value in the output structure will be an empty array.

Note that this implementation assumes that the two input structures have the same field names. If the structures have different field names, you will need to modify the function to handle this case appropriately.

related categories

gistlibby LogSnag