Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...