how to calculate number of unique element in array?

13 ビュー (過去 30 日間)
Putri Basenda Tarigan
Putri Basenda Tarigan 2020 年 11 月 22 日
Hi all.
if I have matrix like:
c =
1 1
1 1
1 1
2 1
2 2
2 3
2 4
2 5
2 5
3 1
3 1
3 2
how can I calculate number of unique element in column 2 according to column 1?
for the above matrix, the result should be:
1 1
2 5
3 2
Thanks in advance

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 22 日
編集済み: Ameer Hamza 2020 年 11 月 22 日
Try splitapply()
c = [
1 1
1 1
1 1
2 1
2 2
2 3
2 4
2 5
2 5
3 1
3 1
3 2]
out = [unique(c(:,1)) ...
splitapply(@(x) numel(unique(x)), c(:,2), c(:,1))]
or accumarray():
out = [unique(c(:,1)) ...
accumarray(c(:,1), c(:,2), [], @(x) numel(unique(x)))];
And if the second column also contain all positive integers in increasing order then you can just try
out = [unique(c(:,1)) ...
splitapply(@max, c(:,2), c(:,1))]
%
out = [unique(c(:,1)) ...
accumarray(c(:,1), c(:,2), [], @max)];
  1 件のコメント
Putri Basenda Tarigan
Putri Basenda Tarigan 2020 年 11 月 22 日
Thankyou so much, it helps a lot

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

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 11 月 22 日
編集済み: Bruno Luong 2020 年 11 月 22 日
c =[
1 1
1 1
1 1
2 1
2 2
2 3
2 4
2 5
2 5
3 1
3 1
3 2 ]
d=unique(c,'rows');
c1=d(:,1);
i=find([true; diff(c1)~=0; true]);
count=diff(i);
c1=c1(i(1:end-1));
t=table(c1,count)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by