Grouping rows on the first column and obtain minimum value on second column

조회 수: 3 (최근 30일)
H_W
H_W 2022년 8월 3일
편집: Adam Danz 2022년 8월 4일
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!

답변 (2개)

Torsten
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)),:)
B = 2×2
13 5 12 5
  댓글 수: 5
Torsten
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
Adam Danz 2022년 8월 3일
편집: Adam Danz 2022년 8월 4일
If I'm understanding correctly, that's what the solutions do in my answer.

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


Adam Danz
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')
B = 2×2
12 5 13 5
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')))
B = 2×2
13 5 12 5

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by