n lowest values of a series

Hello, I'd like to find the n lowest values of a series of datas. "min" fonction does not seem to propose this option. I could use a loop of course, bur I'd like to find a fonction that could do that in 1 time if possible. Thank you for your help Christophe

 Accepted Answer

For large data sets, sort is time-consuming. Then:
x = rand(1, 1e6);
tic;
[min1, ind1] = min(x);
x(ind1) = Inf;
[min2, ind2] = min(x);
y = [min1, min2];
toc
tic;
x = sort(x);
y = x(1:2);
toc
I cannot measure it currently. What are your results?

2 Comments

Elapsed time is 0.148598 seconds.
Elapsed time is 0.109737 seconds.
R2012a - Windows 64-bit
x = rand(1, 1e6);
t1 = 0;
t2 = 0;
for ii = 1:100
tic;
[min1, ind1] = min(x);
x(ind1) = Inf;
[min2, ind2] = min(x);
y = [min1, min2];
t1 = t1+toc;
tic
x = sort(x);
y = x(1:2);
t2 = t2+toc;
end
[t1 t2]
ans =
0.1765 3.4405

Sign in to comment.

More Answers (3)

You can use sort() with the 'ascend' option.
% find smallest 5 values
n = 5;
x = randn(100,1);
y = sort(x,'ascend');
y = y(1:n)
Christophe
Christophe on 30 Mar 2012
Hello Wayne, Jan and Sean, Thanks for your answers. In fact I will use a loop (for) and Inf.
Finally here is my solution :
x = rand(1, 1e6);
for m = 1:50
[mini(m), ind(m)] = min(x);
x(ind(m)) = Inf;
end

Tags

Asked:

on 29 Mar 2012

Community Treasure Hunt

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

Start Hunting!