Sort columns by maximum value?

조회 수: 9 (최근 30일)
Seth
Seth 2013년 12월 17일
댓글: Andrei Bobrov 2013년 12월 19일
Having trouble with this one, how do I sort columns by the maximum value contained within them (must be a single line command)?
For example I have the following matrix:
5 -2 3
-10 6 2
0 0 1
The correct output should be:
3 5 -2
2 -10 6
1 0 0
I have narrowed it down to involving the max(x) command which returns the list of maximal values for each column as such:
5 6 3
But how can I then number these values in ascending order without first sorting them? e.g:
2 3 1
If I could do that then it would be simple to reorder from there. Again this problem seems easy using temporary variables but I have to do it as a single line. Any help appreciated.

답변 (4개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 12월 18일
편집: Azzi Abdelmalek 2013년 12월 18일
We can make it simple
y=x(:,sortrows([max(x);1:size(x,2)]',1)*[0;1])

Sean de Wolski
Sean de Wolski 2013년 12월 17일
편집: Sean de Wolski 2013년 12월 17일
x = [5 -2 3
-10 6 2
0 0 1]
[~,idx] = sort(max(x));
y = x(:,idx)
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2013년 12월 17일
편집: Sean de Wolski 2013년 12월 17일
Personally, I would never recommend doing this operation in a single line because it will just obfuscate it. If you really need to, there's probably a way using arrayfun but it'll look hideous and be unreadable.
Or you could just stack them together :)
[~,idx] = sort(max(x));y = x(:,idx)

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


Azzi Abdelmalek
Azzi Abdelmalek 2013년 12월 17일
x=[5 -2 3
-10 6 2
0 0 1];
y=x(:,setdiff(accumarray(max(x)',(1:size(x,2))'),0,'stable'))
  댓글 수: 1
Andrei Bobrov
Andrei Bobrov 2013년 12월 18일
y=x(:,nonzeros(accumarray(max(x)',(1:size(x,2))')));

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


Andrei Bobrov
Andrei Bobrov 2013년 12월 18일
with subsref
y = x(:,subsref(sortrows([max(x)',(1:size(x,2))'],1),struct('type','()','subs',{{':',2}})))

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by