Search code examples
matlabcell-array

matlab cell array, count number of different elements


I have 2 cell arrays as below:

A = {'S' 'M' 'N' 'E'};
B = {'E' 'M' 'Q' 'S'};

In this case, the number of different elements is 3.

In a number array, I can use length(find(A ~= B)); to easily count number of different elements in one step easily.

Is there something similar for cell array of characters?


Solution

  • EDIT: I think I've misunderstood your question, and you probably meant finding different elements in corresponding positions in the arrays. I still kept my old answer

    Counting different elements at the same position

    yuk's approach with strcmp is correct. However, it works only if the two arrays are of the same size. The generalized solution would be:

    N = min(numel(A), numel(B));
    sum(~strcmp(A(1:N), B(1:N))) + numel(A) + numel(B) - 2 * N
    

    If the arrays are of different length, the "extra" elements in the larger array will be counted as different here.

    Counting different elements in any position

    The most general approach would be using ismember, which does not care about lengths of strings or their position in the array. To count the total number of elements in A and B that are different, just do:

    sum(ismember(A, B)) + sum(ismember(B, A))
    

    The same effect can also be obtained with setdiff (instead of ismember):

    numel(setdiff(A, B)) + numel(setdiff(B, A))
    

    Both ways are valid for any two arrays, not necessarily of equal size.