Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

matlab

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...

like image 796
Abhishek Thakur Avatar asked Jan 03 '13 14:01

Abhishek Thakur


People also ask

How do you find the index of the minimum element of a vector?

vector<int> vec = {4,5,0,1,2,3} ; int min_element_index = min_element(vec. begin(), vec. end()) - vec. begin();


1 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
like image 191
HebeleHododo Avatar answered Sep 24 '22 18:09

HebeleHododo