compare two cell arrays and display the differences in matlab

You can use the setdiff function or the isequal function to compare two cell arrays and display the differences between them.

Here's an example using the setdiff function:

main.m
A = {'apple', 'banana', 'orange', 'pear'};
B = {'apple', 'orange', 'kiwi'};

C1 = setdiff(A,B);
C2 = setdiff(B,A);

fprintf('Elements in A not in B: %s\n', strjoin(C1));
fprintf('Elements in B not in A: %s\n', strjoin(C2));
224 chars
9 lines

Output:

main.m
Elements in A not in B: banana, pear
Elements in B not in A: kiwi
66 chars
3 lines

In this example, we have two cell arrays A and B that we want to compare. We use the setdiff function to find the differences between the two arrays. The C1 array contains the elements that are in A but not in B, while the C2 array contains the elements that are in B but not in A. We then use the strjoin function to display the array elements as a comma-separated list.

Here's an example using the isequal function:

main.m
A = {'apple', 'banana', 'orange', 'pear'};
B = {'apple', 'banana', 'kiwi', 'pear'};

if isequal(A,B)
    fprintf('The arrays are equal\n');
else
    fprintf('The arrays are not equal\n');
    C = setdiff(A,B);
    fprintf('Elements in A not in B: %s\n', strjoin(C));
    C = setdiff(B,A);
    fprintf('Elements in B not in A: %s\n', strjoin(C));
end
350 chars
13 lines

Output:

main.m
The arrays are not equal
Elements in A not in B: orange
Elements in B not in A: kiwi
85 chars
4 lines

In this example, we use the isequal function to compare the two arrays A and B. If the arrays are equal, we display a message saying so. Otherwise, we use the setdiff and strjoin functions to display the differences between the arrays.

related categories

gistlibby LogSnag