MATLAB Answers

Find n minimum values in an array?

687 views (last 30 days)
ME on 15 Apr 2015
Commented: zaid tahir on 5 Mar 2021
I have an array, I need to be able to select 2, or 4 or so on 'n' minimum (smallest) values from the specific array? I know i can use 'min' function but this only gives one smallest value. I do not want to sort the array in order and pick values. is there another way ?????
Nicholas Ayres
Nicholas Ayres on 21 Aug 2020
The "optional second output" of sort is the index order.
[sortedVals,indexes] = sort(myvals);
myVals = [1 0.1 7 10 4];
[sortedVals,indexes] = sort(myVals);
sortedVals = [0.1 1 4 7 10]
indexes = [2 1 5 3 4]
Figured I'd pop this here in case anyone else comes along with the same question. :)

Sign in to comment.

Accepted Answer

Titus Edelhofer
Titus Edelhofer on 15 Apr 2015
if you don't want to sort, and n is not too large, you could remove the index, something like
x = rand(1000, 1);
n = 5;
val = zeros(n,1);
for i=1:n
[val(i),idx] = min(x);
% remove for the next iteration the last smallest value:
x(idx) = [];
zaid tahir
zaid tahir on 5 Mar 2021
@Titus Edelhoferthanks for the code. Helped make a very complex problem, very simple.

Sign in to comment.

More Answers (3)

Jan on 23 Jan 2017
While sorting is the best approach to get the data, you can easily obtain an unsorted result:
n = 2;
[xs, index] = sort(x);
result = x(sort(index(1:n)))

Salam Ismaeel
Salam Ismaeel on 30 Aug 2018
use: mink() command for R2018a
Martin Vankát
Martin Vankát on 25 Oct 2020
Thank you! This one helped.

Sign in to comment.

Titus Edelhofer
Titus Edelhofer on 15 Apr 2015
Edited: Titus Edelhofer on 15 Apr 2015
if it's not floating point but integers (so no problem with roundoff),you could do the following:
x = [1 3 2 4 1 3 5 4 1 3 1]
% find the first 2 min occurrences:
idxMin = find(x==min(x), 2, 'first')
This tells that the smallest value 1 is found at positions 1 and 5. Or are you looking for the n smallest values in the sense, you are looking for the smallest, the second smallest etc.? In this case the answer is simply
n = 2;
xs = sort(x);
% pick the n smallest:
ME on 15 Apr 2015
not entirely, because i don't want to sort the array.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!