Extract top 10 values from each row
3 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
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
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
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!