MATLAB Answers

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

1 view (last 30 days)
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]


Sign in to comment.

Accepted Answer

Sean de Wolski
Sean de Wolski on 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


Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!