필터 지우기
필터 지우기

Finding element with max value in each row of a matrix

조회 수: 1 (최근 30일)
Konstantinos
Konstantinos 2014년 12월 4일
댓글: Konstantinos 2014년 12월 4일
How can I find the 4 elements with the largest values in each row of a matrix ? Moreover, I would like to know the exact position of them in each row.
i.e. A(2X8) = [ 1 2 3 4 8 5 2 9 ; 5 6 4 7 9 1 1 2; ]
For the above matrix the answer would be:
1st row max values elements: 4, 8, 5, 9
1st row position of these elements: 4, 5, 6, 8
2nd row max values elements: 5, 6, 7, 9
2nd row position of these elements: 1, 2, 4, 5
Any help could be useful.
Thanks in advance!

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 12월 4일
편집: Azzi Abdelmalek 2014년 12월 4일
a=[ 1 2 3 4 8 5 2 9 ; 5 6 4 7 9 1 1 2; ]
[ii,jj]=sort(a,2,'descend')
v=ii(:,1:4)
idx=jj(:,1:4)

추가 답변 (1개)

Guillaume
Guillaume 2014년 12월 4일
편집: Guillaume 2014년 12월 4일
sort your matrix by column and in descending order. The first argument returned are the max, the second their indices:
A = [1 2 3 4 8 5 2 9 ; 5 6 4 7 9 1 1 2]
[maxvals, maxindices] = sort(A, 2, 'descend');
maxvals = maxvals(:, 1:4)
maxindices = maxindices(:, 1:4)
  댓글 수: 3
Guillaume
Guillaume 2014년 12월 4일
Yes, I forgot the colon initially. However, I corrected that mistake before you made the comment.
My answer is identical to Azzi's except mine got some explanation (and useful variable names).
Konstantinos
Konstantinos 2014년 12월 4일
You are correct! thanks for your help!

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

카테고리

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