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

1 Ansicht (letzte 30 Tage)
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]

Akzeptierte Antwort

Sean de Wolski
Sean de Wolski am 3 Feb. 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

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by