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

1 vue (au cours des 30 derniers jours)
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]

Réponse acceptée

Sean de Wolski
Sean de Wolski le 3 Fév 2020
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

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by