필터 지우기
필터 지우기

group an array according a condition

조회 수: 3 (최근 30일)
eric capnu
eric capnu 2017년 8월 9일
댓글: eric capnu 2017년 9월 1일
Hi everyone
i have an array like this
A=
2 10 10.1 12 14 110
2 10.1 11 12 15 145
3 12 12 12 24 223
3 12 11.4 11 23 100
3 10 12 20 18 211
4 9 23 11 11 98
I want to create a new B array where i get the maximum value of each column according to the first column value
B=
2 10.1 11 12 15 145
3 12 12 20 24 223
4 9 23 11 11 98
i don´t want to use loops. is there a way to do it by using just matlab functions?
thanks in advance

채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 8월 9일
편집: Andrei Bobrov 2017년 8월 10일
B_table = varfun(@max,array2table(A),'GroupingVariables','A1')
or
B = splitapply(@(x)max(x,[],1),A,findgroups(A(:,1)));
or
g = findgroups(A(:,1)); % or >> [~,~,g] = unique(A(:,1))
[ii,jj] = ndgrid(g,1:size(A,2));
B = accumarray([ii(:),jj(:)],A(:),[],@max);
  댓글 수: 2
John BG
John BG 2017년 8월 10일
편집: John BG 2017년 8월 10일
and then back to array
B=table2array(Btable)
B =
2.0000 2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 1.0000 9.0000 23.0000 11.0000 11.0000 98.0000
no need for the frequencies
B(:,2)=[]
B =
2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 9.0000 23.0000 11.0000 11.0000 98.0000
eric capnu
eric capnu 2017년 9월 1일
thanks mates. that was very useful... and, what if instead of @max it would be the last element or the first element of the range?

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

추가 답변 (1개)

Stephen23
Stephen23 2017년 8월 9일
편집: Stephen23 2017년 8월 9일
You could use accumarray:
A = [
2 10 10.1 12 14 110
2 10.1 11 12 15 145
3 12 12 12 24 223
3 12 11.4 11 23 100
3 10 12 20 18 211
4 9 23 11 11 98];
%
[~,~,X] = unique(A(:,1));
V = 1:size(A,1);
fun = @(r){max(A(r,:),[],1)};
C = accumarray(X,V(:),[],fun);
Z = vertcat(C{:})
produces this:
Z =
2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 9.0000 23.0000 11.0000 11.0000 98.0000

카테고리

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