how to determine the number of spesific string in cell?

2 Ansichten (letzte 30 Tage)
Ruslan Wahyudi
Ruslan Wahyudi am 15 Feb. 2015
Beantwortet: Geoff Hayes am 15 Feb. 2015
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..

Antworten (2)

Star Strider
Star Strider am 15 Feb. 2015
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 am 15 Feb. 2015
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!

Kategorien

Mehr zu Data Type Identification finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by