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

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

Leave a Comment