我无法弄清楚如何计算单元格中字符串中字符的出现次数。例如,我有一个包含如下信息的文件:
type
m
mmNs
SmNm
我正在尝试确定每行中有多少个m。为此,我尝试了这段代码:
sampleddata = dataset('file','sample.txt','Delimiter','\t');
muts = sampleddata.type;
fileID = fopen('number_occur.txt','w');
for j = 1:3
mutations = muts(j)
M = length(find(mutations == 'm'));
fprintf(fileID, '%1f\n',M)
end
fclose(fileID)
但是,我收到一条错误通知我:“未定义的运算符'=='表示'cell'类型的输入参数。”有谁知道如何克服这个问题?
答案 0 :(得分:2)
要在此处发布结果,以防您找不到方法。有很多方法可以做到,我只想把它们中的一个。
基本上,你想要一个正则表达式来进行字符串匹配:
a = {'type';
'm';
'mmNs';
'SmNm';
'mmmmM'} %//Load in Data,
pattern = 'm'; %//The pattern you are looking for is 'm', it could be anything really, a number of specific word or a specific pattern
lines = regexp(a, pattern, 'tokens'); %// look for this pattern in each line
result = cellfun('length',lines); %//count the size of matched patterns, so each time it matches, the size should increase by 1.
这以矩阵形式给出结果:
result =
0
1
2
2
4