单元格数组中存在字符串的次数

时间:2016-04-14 10:52:10

标签: arrays matlab count cell

我有阵列

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

和单元格数组

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' '' ''}

我想知道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 

对于

中的所有字符串都是一样的

我想输出一个数组,其中a中字符串的数量是b中的,你能帮帮我吗?

如果问题不明确,我会尝试更好地解释

1 个答案:

答案 0 :(得分:3)

如果S1和S2相同,则

strcmp(S1,S2)返回1。使用find查找哪些索引包含您要查找的字符串,然后检查返回向量的length。最后,将其转换为num2str的字符串。现在您有b中字符串出现的次数。

以下是代码:

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 = 

'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'