Find Number of Elements in an Array
30 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Burak Alakus
am 19 Aug. 2019
Kommentiert: Adam Danz
am 5 Jun. 2024
Hello guys. I want to find the number of elements in a string array.
Lets say A = ['KM'; 'KL'; 'MN'; 'KM', 'MM', 'KL'] is my array list.
It should give output as;
[2,2,1,1] since my string array includes 2 KM, 2 KL, 1MN, and 1MM.
How can i do that?
0 Kommentare
Akzeptierte Antwort
Lola Davidson
am 4 Jun. 2024
If you prefer avoiding cell arrays and/or tables, groupcounts (introduced in R2019a) can do this straight away
A = ['KM'; 'KL'; 'MN'; 'KM'; 'MM'; 'KL'];
groupcounts(A)
That said, if you like the decoration, you can put it in a table before sending it to groupcounts.
A = ["KM"; "KL"; "MN"; "KM"; "MM"; "KL"];
groupcounts(table(A),1)
0 Kommentare
Weitere Antworten (3)
Adam Danz
am 19 Aug. 2019
The "A" array provided in the question will result in a dimensions mismatch error. I'm assuming A is an [nx2] char array.
A = ['KM'; 'KL'; 'MN'; 'KM'; 'MM'; 'KL'];
% Convert char array to cell array of strings
Acell = cellstr(A);
% Find groups of strings
[groups, groupID]= findgroups(Acell(:));
% Count members of each group
count = sum(groups(:).' == unique(groups(:)),2);
% Display results in a table
countTable = table(groupID(:),count(:),'VariableNames',{'Group','Count'});
Result
countTable =
4×2 table
Group Count
_____ _____
'KL' 2
'KM' 2
'MM' 1
'MN' 1
3 Kommentare
Adam Danz
am 5 Jun. 2024
June 5, 2024 - I unaccepted this answer in favor of Lola's better solution using groupcounts that became available in R2019a. Prior to R2019a, I would recommend Steven Lord's answer.
Andrei Bobrov
am 19 Aug. 2019
Bearbeitet: Andrei Bobrov
am 19 Aug. 2019
A = {'KM'; 'KL'; 'MN'; 'KM'; 'MM'; 'KL'};
out = varfun(@x,table(A),'GroupingVariables','A')
Steven Lord
am 4 Jun. 2024
Yet another way to do this:
A = ['KM'; 'KL'; 'MN'; 'KM'; 'MM'; 'KL'];
[counts, values] = histcounts(categorical(cellstr(A)))
0 Kommentare
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!