Grouping rows on the first column and obtain minimum value on second column
1 回表示 (過去 30 日間)
古いコメントを表示
I have the following matrix A and would like to group it on the first column
A = [13 7
13 6
13 5
13 6
12 7
12 5];
and then obtain minimum value on second column to obtain matrix B
B = [13 5
12 5];
Could anyone give a hint?
Thanks!
0 件のコメント
回答 (2 件)
Torsten
2022 年 8 月 3 日
編集済み: Torsten
2022 年 8 月 3 日
What do you mean by "group on the first column" ?
A = [13 7
13 6
13 5
13 6
12 7
12 5];
A = sortrows(A,2,'ascend');
B = A(1:nnz(A(:,2)==A(1,2)),:)
5 件のコメント
Torsten
2022 年 8 月 3 日
So for all distinct values in the first column, you want to get one pair where the value in the second column is minimum ? Is it necessary to group the first column first (e.g. sort in ascending/descending order) or is this already done in A ?
Adam Danz
2022 年 8 月 3 日
編集済み: Adam Danz
2022 年 8 月 3 日
A = [13 7
13 6
13 5
13 6
12 7
12 5];
B = groupsummary(A,A(:,1),'min')
Note that rows are sorted according to the grouping column values.
To keep the row order stable there are several options but I lean on arrayfun which is less readable than other options.
B = cell2mat(arrayfun(@(g){min(A(A(:,1)==g,:))}, unique(A(:,1),'stable')))
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!