compare the content of two cell arrays if they are the same even when the input is arranged differently in matlab

One way to do this is to first sort the cell arrays along a specific dimension to ensure that the elements are arranged in a consistent order before comparison. Here's an example:

main.m
% sample cell arrays
A = {1, 2, 3; 'a', 'b', 'c'};
B = {2, 1, 3; 'b', 'a', 'c'};

% sort along rows (dimension 1)
A_sorted = sortrows(A);
B_sorted = sortrows(B);

% compare sorted arrays
if isequal(A_sorted, B_sorted)
    disp('Cell arrays are the same!');
else
    disp('Cell arrays are different.');
end
306 chars
15 lines

In this example, the sortrows function is used to sort the cell arrays along the rows. Alternatively, if you want to sort along the columns, you can use the sortrows function with the transpose of the cell array (sortrows(A.'), for example).

Note that the isequal function is used to compare the sorted arrays. This function checks if the two arrays are exactly the same, including their size and element values. If you only want to check if the arrays are approximately the same (i.e., within a certain tolerance), you can use the isequaltol function instead.

You can modify this code to work for cell arrays with different dimensions by specifying the dim argument in sortrows, or by using the sort function with the appropriate dimension.

Additionally, if you want to ignore the case of strings or characters, you can use the lower function to convert them to lowercase before sorting.

gistlibby LogSnag