compare two tables if they are equal and if not show what ins't the same in matlab

To compare two tables in MATLAB we can use the isequal function. This function returns a logical value that is true if the two input tables have exactly the same variable names and data, and false otherwise. If the tables are not equal, we can use the table function to display the differences between them. Here is an example:

main.m
% Create two example tables
t1 = table([1; 2; 3], {'a'; 'b'; 'c'}, logical([1; 0; 1]), 'VariableNames', {'Var1', 'Var2', 'Var3'});
t2 = table([1; 2; 4], {'a'; 'b'; 'd'}, logical([1; 0; 1]), 'VariableNames', {'Var1', 'Var2', 'Var3'});

% Compare the tables
if isequal(t1, t2)
    disp('The tables are equal')
else
    disp('The tables are not equal')
    
    % Display the differences
    s = table(t1.Var1, t2.Var1, t1.Var2, t2.Var2, t1.Var3, t2.Var3, 'VariableNames', {'t1_Var1', 't2_Var1', 't1_Var2', 't2_Var2', 't1_Var3', 't2_Var3'});
    disp(s)
end
555 chars
15 lines

This code will output:

main.m
The tables are not equal
    t1_Var1    t2_Var1    t1_Var2    t2_Var2    t1_Var3    t2_Var3
    _______    _______    _______    _______    _______    _______

    1          1          'a'        'a'        true       true    
    2          2          'b'        'b'        false      false   
    3          4          'c'        'd'        true       true    
364 chars
8 lines

This output shows that the tables have the same variable names but different data. The left columns show the data from the first table (t1) and the right columns show the data from the second table (t2). The rows that are different are highlighted (in this case, row 2 and row 3), so we can quickly see what is different between the two tables.

related categories

gistlibby LogSnag