A.Rainer
A.Rainer

Reputation: 719

Counting the occurence of substrings in matlab

I have a cell, something like this P= {Face1 Face6 Scene6 Both9 Face9 Scene11 Both12 Face15}. I would like to count how many Face values, Scene values, Both values in P. I don't care about the numeric values after the string (i.e., Face1 and Face23 would be counted as two). I've tried the following (for the Face) but I got the error "If any of the input arguments are cell arrays, the first must be a cell array of strings and the second must be a character array".

strToSearch='Face';
numel(strfind(P,strToSearch));

Does anyone have any suggestion? Thank you!

Upvotes: 2

Views: 800

Answers (2)

nkjt
nkjt

Reputation: 7817

Your example should work with some small tweaks, provided all of P contains strings, but may give the error you get if there are any non-string values in the cell array.

P= {'Face1' 'Face6' 'Scene6' 'Both9' 'Face9' 'Scene11' 'Both12' 'Face15'};
strToSearch='Face';
n = strfind(P,strToSearch);
numel([n{:}])

(returns 4)

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

Use regexp to find strings that start (^) with the desired text (such as 'Face'). The result will be a cell array, where each cell contains 1 if there is a match, or [] otherwise. So determine if each cell is nonempty (~cellfun('isempty', ...): will give a logical 1 for nonempty cells, and 0 for empty cells), and sum the results (sum):

>> P = {'Face1' 'Face6' 'Scene6' 'Both9' 'Face9' 'Scene11' 'Both12' 'Face15'};
>> sum(~cellfun('isempty', regexp(P, '^Face')))
ans =
     4

>> sum(~cellfun('isempty', regexp(P, '^Scene')))
ans =
     2

Upvotes: 3

Related Questions