필터 지우기
필터 지우기

Find Number of Elements in an Array

조회 수: 15 (최근 30일)
Burak Alakus
Burak Alakus 2019년 8월 19일
댓글: Adam Danz 2024년 6월 5일
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?

채택된 답변

Lola Davidson
Lola Davidson 2024년 6월 4일
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)
ans = 4x1
2 2 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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)
ans = 4x3 table
A GroupCount Percent ____ __________ _______ "KL" 2 33.333 "KM" 2 33.333 "MM" 1 16.667 "MN" 1 16.667

추가 답변 (3개)

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
  댓글 수: 3
Adam Danz
Adam Danz 2019년 8월 20일
Glad I could help and learn along with ya!
Adam Danz
Adam Danz 2024년 6월 5일
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
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.

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2024년 6월 4일
Yet another way to do this:
A = ['KM'; 'KL'; 'MN'; 'KM'; 'MM'; 'KL'];
[counts, values] = histcounts(categorical(cellstr(A)))
counts = 1x4
2 2 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
values = 1x4 cell array
{'KL'} {'KM'} {'MM'} {'MN'}

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by