Find Number of Elements in an Array

22 ビュー (過去 30 日間)
Burak Alakus
Burak Alakus 2019 年 8 月 19 日
コメント済み: Adam Danz 2019 年 8 月 20 日
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?

採用された回答

Adam Danz
Adam Danz 2019 年 8 月 19 日
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
  2 件のコメント
Burak Alakus
Burak Alakus 2019 年 8 月 20 日
Thank you Mr. Danz. This answer really helped me.
Adam Danz
Adam Danz 2019 年 8 月 20 日
Glad I could help and learn along with ya!

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2019 年 8 月 19 日
編集済み: Andrei Bobrov 2019 年 8 月 19 日
A = {'KM'; 'KL'; 'MN'; 'KM'; 'MM'; 'KL'};
out = varfun(@x,table(A),'GroupingVariables','A')
  1 件のコメント
Burak Alakus
Burak Alakus 2019 年 8 月 20 日
Thank you Mr. Bobrov. This answer really helped me.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by