how to determine the number of spesific string in cell?
2 ビュー (過去 30 日間)
古いコメントを表示
i have a data cell contain x={'ab','cd','cd','ab','ab','ef'}; if we see in the data, its contain three 'ab' String, two 'cd' string, and one 'ef' string. how can i determine it in matlab code? i am new in matlab, thank you very much..
0 件のコメント
回答 (2 件)
Star Strider
2015 年 2 月 15 日
One approach:
x={'ab','cd','cd','ab','ab','ef'};
[Ux, ~, ic] = unique(x);
[Cts] = histc(ic, [1:length(Ux)]);
out = {Ux', Cts};
for k1 = 1:length(Cts)
fprintf('\t%s = %d\n', char(out{1}(k1)), out{2}(k1))
end
produces:
ab = 3
cd = 2
ef = 1
Experiment to get the result you want.
0 件のコメント
Geoff Hayes
2015 年 2 月 15 日
Rusian - you could first sort the contents of the cell array so that all identical elements follow each other
x = {'ab','cd','cd','ab','ab','ef'};
sX = sort(x);
where sX is
sX =
'ab' 'ab' 'ab' 'cd' 'cd' 'ef'
You could then iterate over each element comparing it with the previous one. If there is a difference, then you know that you have encountered all those of the previous strings and can just write out their count. Something like
distinctStrings = {};
atString = 1;
count = 1;
for k=2:length(sX)
if strcmp(sX{k},sX{k-1}) == 1
% the two strings are identical so increment the count
count = count + 1;
else
% the two strings are not identical so update distinctStrings
% and reset the counter
distinctStrings{atString,1} = sX{k-1};
distinctStrings{atString,2} = count;
count = 1;
atString = atString + 1;
end
if k==length(sX)
% on the last element so insert it into array
distinctStrings{atString,1} = sX{k};
distinctStrings{atString,2} = count;
end
end
where distinctStrings is
distinctStrings =
'ab' [3]
'cd' [2]
'ef' [1]
Try the above and see what happens!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Type Identification についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!