kikki
kikki

Reputation: 31

how many times a string is present in a cell array

I have the array

a={'2';'23';'231';'2312';'23121';'231213';'3';'31'}

and the cell array

b={'2' '21' '' '' '' '' '';'3' '32' '' '' '' '' '';'2' '24' '242' '2423' '' '' '';'(34)' '(34)2' '' '' '' '' '';'4' '43' '432' '4323' '' '' '';'3' '32' '321' '3212' '32124' '321243' '';'3' '34' '343' '3432' '34323' '' '';'(34)' '(34)3' '' '' '' '' '';'2' '21' '212' '' '' '' '';'3' '32' '323' '' '' '' '';'4' '41' '413' '4132' '41321' '413213' '4132132';'3' '34' '342' '3423' '34232' '342321' '';'4' '42' '421' '4212' '42124' '' '';'4' '43' '432' '4324' '' '' '';'4' '43' '432' '4323' '43234' '' ''}

I want to know how many times the string in a are present in b

eg string '2' is present 3 times
   string '23' is present 0 times
   string '231' is present o times
   string '3' is present 5 times 

it's the same for the all strings in a

I want like output an array with the number of times strings in a are presents in b, can you help me?

If the question is not clear, I try to explain better

Upvotes: 1

Views: 52

Answers (1)

jkazan
jkazan

Reputation: 1199

strcmp(S1,S2) returns 1 if S1 and S2 are the same. Use find to find which indices contain the string you are trying to find and then check the length of the returned vector. Finally, turn this into a string with num2str. Now you have the number of times a string is present in b.

Here's the code:

result = cell(length(a),1);
for k = 1:length(a)
    result{k} = sprintf('string ''%s'' is present %d times', a{k},  length(find(strcmp(b,a(k)))));
end

Result:

result = 

'string '2' is present 3 times'
'string '23' is present 0 times'
'string '231' is present 0 times'
'string '2312' is present 0 times'
'string '23121' is present 0 times'
'string '231213' is present 0 times'
'string '3' is present 5 times'
'string '31' is present 0 times'

Upvotes: 3

Related Questions