Search code examples
matlabcell-array

Comparing cell arrays of different types in matlab


Premise: I found something that seems to be related to my problem, but I'm not sure how to use it, thus I'm asking a new question.

I have a cell matrix, call it A, which would look something like this:

[ 'string' 'string' 'number'

'string' 'string' 'number'

........................... ]

and I need to compare a cell array I just created, call it B = ['string' 'string' 'number'], with matrix A to see if B is already there somwhere. If I try touse ismember, matlab returns an error because an argument is not a string.

What should I do?

Thanks for the help


Solution

  • Your question is a bit unclear, so this answer is only valid if these assumptions are:

    • You really mean cell arrays and not char arrays in 2nd dimension as your code snippets suggest.
    • Your cell arrays A and B have the same number of elements in the 2nd dimension.

    The following line will return a column vector of ones and zeros, where a one indicate a match of the B elements with a row in X:

    sum(cellfun(@isequal,X,repmat(B,size(X,1),1)),2)==size(X,2)
    

    Brief explanation:

    • repmat replicates B to the size of X.
    • cellfun compares every single element in the two matrices.
    • sum counts the number of string matches in each row.
    • == checks if all elements in a given row matches.

    Hope it helps