2

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!

0

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer and the explanation, Luis! Using regexp intimidates me, though.
That's part of the fun of regexp :-) Anyway, this one regular expression is very simple: just the ^ to indicate start
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.