How can I find the max and min amongst a set of grouping variables?

조회 수: 7 (최근 30일)
I have a 150x2 matrix in which the first column contains numbers that can be considered 'grouping variables' and the second column contains values associated with those grouping variables. So a small 6x2 version would look like this
1 23
1 29
1 43
2 38
2 22
2 100
I'd like to find the maximum of the values associated with each grouping variable. Similarly the minimum amongst the values associated with each grouping variable. So the above example would yield an max of 43(for variable 1) and min of 23 (for variable 1). Similarly, max of 100 (for variable 2) and min of 22 (for variable 2). Does anybody know of a similar function or method to achieve this in Matlab?

채택된 답변

Michael Haderlein
Michael Haderlein 2015년 2월 3일
Since you didn't write if every number will occur in the first column, I allow for "missing" numbers here (it doesn't make a big difference anyway):
a=1+fix(0:.23:8)' ;
b=randi(50,length(a),1);
M=[a b]
nums=unique(M(:,1));
mmin=zeros(max(nums),1);
mmax=zeros(max(nums),1);
for cnt=1:max(nums)
mmin(nums(cnt))=min(M(M(:,1)==nums(cnt),2));
mmax(nums(cnt))=max(M(M(:,1)==nums(cnt),2));
end
If every number will occur, nums(cnt)==cnt, so the expressions inside the loop can be simplified a bit.
  댓글 수: 1
Prateek Samuel Daniels
Prateek Samuel Daniels 2015년 2월 3일
Thank u so much Michael. Never in my wildest dreams did I think that people would reply so fast and come up with accurate answers.

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

추가 답변 (1개)

David Young
David Young 2015년 2월 3일
% test data
data = [1 23; 1 29; 1 43; 2 38; 2 22; 2 100];
% compute minima and maxima
mins = accumarray(data(:,1), data(:,2), [], @min);
maxs = accumarray(data(:,1), data(:,2), [], @max);
Then mins(k) and maxs(k) hold the min and max for grouping variable k.
  댓글 수: 3
Prateek Samuel Daniels
Prateek Samuel Daniels 2015년 2월 3일
편집: Prateek Samuel Daniels 2015년 2월 3일
Thank u David. I've tried going thru the documentation on accumarray and I couldn't understand why and how it was used. But when I saw your response, things were pretty clear, except for the [] (the 3rd argument). Why do we need to put that. would it be possible for you to recommend me any matlab advanced/ intermediate book which covers these functions and its usage. Many thanks !!!
David Young
David Young 2015년 2월 3일
The third argument specifies the size of the output array, but if you're happy to let it be determined by the values in the first argument you can just let it default by putting [].
I'm afraid I don't know which books cover relatively recent functions like accumarray.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by