2

How can I get the smallest n elements of a 1D array

example

A = [29, 60, 96, 43, 69, 53];
n=3;
%so B will be like this
B = [29 43 53];
Dan
  • 45,079
  • 17
  • 88
  • 157
mttb12
  • 75
  • 1
  • 9
  • possible duplicate of [How to find the index of the n smallest elements in a vector](http://stackoverflow.com/questions/14140746/how-to-find-the-index-of-the-n-smallest-elements-in-a-vector), [Pick x smallest elements in Matlab](http://stackoverflow.com/questions/16040391/pick-x-smallest-elements-in-matlab) and [Find n minimum values in an array](http://stackoverflow.com/questions/14774860/find-n-minimum-values-in-an-array)... – Eitan T Apr 24 '13 at 14:24

1 Answers1

4

Try this:

B = sort(A);    %# sort in ascending order
B = B(1:n);     %# take the first N-values
Amro
  • 123,847
  • 25
  • 243
  • 454