Is there a way to get the top k values per row of a MATLAB array?

1 回表示 (過去 30 日間)
Jesujoba Alabi
Jesujoba Alabi 2020 年 2 月 3 日
回答済み: Sean de Wolski 2020 年 2 月 3 日
Given a MATLAB matrix of the form below:
x = [4.,3.,2.,1.,8. ; 1.2,3.1,0.,9.2,5.5 ; 0.2,7.0,4.4,0.2,1.3]
is there a way to retain the top-3 values in each row and set others to zero in MATLAB. The result in the case of the example above would be
x = [4.,3.,0.,0.,8.; 0.,3.1,0.,9.2,5.5; 0.0,7.0,4.4,0.0,1.3]

採用された回答

Sean de Wolski
Sean de Wolski 2020 年 2 月 3 日
I'd probably do something like this:
x = magic(4)
k = 3
[~,idx] = maxk(x,k,2)
for ii = 1:size(x,1)
x(ii,~ismember(1:size(x,2), idx(ii,:))) = 0
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by