Search code examples
arraysmatlabcell

Count items in one cell array in another cell array matlab


I have 2 cell arrays which are "celldata" and "data" . Both of them store strings inside. Now I would like to check each element in "celldata" whether in "data" or not? For example, celldata = {'AB'; 'BE'; 'BC'} and data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '}. I would like the expected output will be s=3 and v= 1 for AB, s=2 and v=2 for BE, s=2 and v=2 for BC, because I just need to count the sequence of the string in 'celldata'

The code I wrote is shown below. Any help would be certainly appreciated. My code:

s=0; support counter
v=0; violate counter
SV=[]; % array to store the support
VV=[]; % array to store the violate

pairs = ['AB'; 'BE'; 'BC']
%celldata = cellstr(pairs)
celldata = {'AB'; 'BE'; 'BC'}
data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '} % 3 AB, 2 BE, 2 BC

for jj=1:length(data)
    for kk=1:length(celldata)

res = regexp( data(jj),celldata(kk) )

m = cell2mat(res);
e=isempty(m)  % check res array is empty or not
if e == 0
    s = s + 1;
    SV(jj)=s;
    v=v;
else
    s=s;
    v= v+1;
    VV(jj)=v;
end
    end
end

Solution

  • If I am understanding your variables correctly, s is the number of cells which the substring AB, AE and, BC does not appear and v is the number of times it does. If this is accurate then

    v = cellfun(@(x) length(cell2mat(strfind(data, x))), celldata);
    s = numel(data) - v;
    

    gives

    v = [1;1;3];
    s = [3;3;1];