Extract top 10 values from each row

조회 수: 4 (최근 30일)
Saurabh
Saurabh 2011년 10월 10일
Hello,
I have a matrix and wish to keep only the top 10 values in each row and replace all the other (bottom 90) values with zeros. Is there an efficient way to achieve this?

채택된 답변

Walter Roberson
Walter Roberson 2011년 10월 10일
[sortvals, sortidx] = sort(A,'descend');
B = zeros(size(A),class(A));
for K = 1 : size(A,2)
B(sortidx(1:10,K),K) = sortvals(1:10,K);
end
Yes, it could probably be done without a loop, using sub2ind(), but that would not necessarily be any faster, and would probably be less clear.
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 10월 10일
Adjusting for rows:
[sortvals, sortidx] = sort(A,2,'descend');
B = zeros(size(A),class(A));
for K = 1 : size(A,1)
B(K,sortidx(K,1:10)) = sortvals(K,1:10);
end

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

추가 답변 (1개)

Laura Proctor
Laura Proctor 2011년 10월 10일
This code will keep the top ten rows and replaces everything from the 11th row on with a zero.
A = rand(100);
A(11:end,:) = 0;
  댓글 수: 4
Saurabh
Saurabh 2011년 10월 10일
Oh, I meant 'top 10' as in the maximum 10 values.
Example, for simplicity, consider the top 2 values
A =
1 2 3 4
4 3 2 5
6 5 4 2
1 4 2 3
Then I want the output as
B =
0 0 3 4
4 0 0 5
6 5 4 2
0 4 0 3
Thus, the top two values of each row are kept and others are replaced with zeros.
Saurabh
Saurabh 2011년 10월 10일
I answered a bit late.
Laura: That method would work, but it destroys the element order. I wish to preserve the order as in above example.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by