Search code examples
stringmatlabcell-array

Count cells with a specific word in cell array in MATLAB


Suppose that we have this cell array :

X = {'Good' 'Bad' 'Good'; 
     'Bad' 'Good' 'Bad'; 
     'Bad' 'Bad' 'Bad'; 
     'Good' 'Bad' 'Good'; 
     'Good' 'Good' 'Good'};

How can I count occurrences of Good and Bad in every row?

Thanks.


Solution

  • Assuming you have equal number of elements or cells per row in such an input cell array, a fast solution for count of {'Good'} cells per row -

    count = sum(strcmp(X,{'Good'}),2)
    

    Use the same rule for {'Bad'}.


    If strcmp drags you slow, you can use char instead with my personal favorite bsxfun.

    For {'Good'} -

    Xchar = char(X{:})
    count = sum(reshape(all(bsxfun(@eq,Xchar(:,1:numel('Good')),'Good'),2),size(X)),2)
    

    For {'Bad'} -

    count = sum(reshape(all(bsxfun(@eq,Xchar(:,1:numel('Bad')),'Bad'),2),size(X)),2)