Tips & Tricks
Follow


Mike Croucher

Want the smallest 10 elements of a large vector?

Mike Croucher on 3 Oct 2023
Latest activity Edit by Matt J on 14 Oct 2023

Imagine x is a large vector and you want the smallest 10 elements. How might you do it?
Matt J
Matt J on 14 Oct 2023 (Edited on 14 Oct 2023)
It's a good function to be aware of. Unfortunately, it lacks the "linear" flag, which min() has, to allow the locations of the minima to be returned as linear indices. So, I attach my wrapper.
>> A=randi(10,5,2)
A =
6 3
4 4
7 1
4 4
3 6
>> [minvals,I]=minklidx(A,2)
minvals =
3 1
4 3
I =
5 8
2 6
Adam Danz
Adam Danz on 3 Oct 2023 (Edited on 3 Oct 2023)
mink feels particularly warm and cozy when searching for minimum magnitudes, ignoring sign.
a = [0 -2 3 -1 1 -9];
🥇 b = mink(a, 4, ComparisonMethod="abs")
[0 1 -1 -2]
Versus
😒 [~, aidx] = sort(abs(a));
😒 b = a(aidx(1:4))
[0 -1 1 -2]
🔎 Interesting difference in how ties are indexed between the two outputs above (hint).
😒 [~, aidx] = sort(a,ComparisonMethod="abs");
😒 b = a(aidx(1:4))
[0 1 -1 -2]
Ned Gulley
Ned Gulley on 3 Oct 2023
Uh-oh! Mike has found a new outlet for his memes vice!
(also: cool hack!)

See Also

Tags

No tags entered yet.