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

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by