image thumbnail

comparedata

version 1.0.0.0 (3.49 KB) by Andrew Diamond
Compares two objects recursively.

3.9K Downloads

Updated 05 Mar 2002

No License

Compares two objects recursively, like isequal, but notes differences. Returns 1 if roughly equal where equal can be relaxed to include just the matching fields of structures (or recursive substructures) and/or numeric differences that are under a specified tolerance (default 1e-10). Intermediate comparison results can be printed to file and/or screen.

Help is at top of file.

Note, uses MATLAB's "isequal" function at any recursion level whose object is not a cell, struct, or numeric array.

Example 1: comparison of two simple structures noting but not taking into account fields that are unique to one of the objects.:
>> s1.a=1; s1.b=2; s1.c=3; s2.a=1; s2.b=2;
>> retval=comparedata(s1, s2, [], struct('ignoreunmatchedfieldnames', 1))

context = Top
Mismatch in Top.c not found in second structure
context = Top.a
context = Top.b
retval = 1

Example 2: Comparing nested structures with array elements that are only roughly equal but good enough for the specified tolerance of 0.001. Results printed to screen and file comparedata.out.

>> P1 = struct('s1', struct('s11',[1,2;3,4]));
>> P2 = struct('s1', struct('s11',[1,2;3,4+1e-9]));
>> comparedataParams = struct('NumericTolerance',0.001,'outfileorfid','comparedata.out');
>> retval=comparedata(P1,P2, '',struct('NumericTolerance',0.001,'outfileorfid','comparedata.out'))
context = Top
context = Top.s1
context = Top.s1.s11

retval =

1

Example 3: Building on example 2 with arrays of nested structures. Parameters set to just print to screen and to use default numeric tolerance of 1e-10.
>> aP1 = [P1,P1]; aP2 = [P2, P2]; % create arrays of structures to compare.
>> retval=comparedata(aP1,aP2)
context = Top
context = Top[1, 1].s1
context = Top[1, 1].s1.s11
Mismatch : at Top[1, 1].s1.s11 numeric array comparison - abs(data 1 - data 2) > tolerance of 1e-010:
mindiff = -1.000000e-009 at [2, 2]
maxdiff = 0.000000e+000 at [1, 1]
max abs diff = 1.000000e-009 at [2, 2]
context = Top[1, 2].s1
context = Top[1, 2].s1.s11
Mismatch : at Top[1, 2].s1.s11 numeric array comparison - abs(data 1 - data 2) > tolerance of 1e-010:
mindiff = -1.000000e-009 at [2, 2]
maxdiff = 0.000000e+000 at [1, 1]
max abs diff = 1.000000e-009 at [2, 2]

retval =

0

Cite As

Andrew Diamond (2022). comparedata (https://www.mathworks.com/matlabcentral/fileexchange/1459-comparedata), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R12.1
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!