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

回答(2 个)

Star Strider
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.

Geoff Hayes
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!

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by