How to find the index of the n smallest elements in a vector

How can I get the indices of "n smallest elements" in a 1D array in MATLAB?

The array is a row vector.

I can find the smallest element and its index using ;

[C, ind] = min(featureDist);

The vector is like:

featureDist =

  Columns 1 through 8

   48.4766   47.3743   59.5736   59.7450   55.0489   58.2620   63.3865   50.1101

and so on...

Answers


You can use the sort function. To get the smallest n elements, you can write a function like this:

function [smallestNElements smallestNIdx] = getNElements(A, n)
     [ASorted AIdx] = sort(A);
     smallestNElements = ASorted(1:n);
     smallestNIdx = AIdx(1:n);
end

Let's try with your array:

B = [48.4766 47.3743 59.5736 59.7450 55.0489 58.2620 63.3865 50.1101];
[Bsort Bidx] = getNElements(B, 4);

returns

BSort = 
    47.3743   48.4766   50.1101   55.0489
Bidx = 
    2 1 8 5

I know this is an extremely late reply but I am hoping to help anyone who may have this question later.

If A is the array of elements, yu could try using the find function to determine the index of the n smallest elements.

[~, idx] = find(A > -Inf, n, 'first')

To determine the n largest elements,

[~, idx] = find(A < Inf, n, 'last')


Need Your Help

Where can I find an actively developed lint tool for Ruby?

ruby code-analysis static-analysis lint

Most of the code I write is in Ruby, and every once in a while, I make some typo which only gets caught after a while. This is irritating when I have my scripts running long tasks, and return to fi...

VS2010 and IE10 Attaching the Script debugger to process iexplore.exe failed

visual-studio-2010 visual-studio internet-explorer-10 windows-7-x64

So I am using Win7 x64 with VS2010 and have installed the IE10 Win7 Preview and ReSharper 6.1.