如何找到向量中 n 个最小元素的索引 [英] How to find the index of the n smallest elements in a vector

查看:26
本文介绍了如何找到向量中 n 个最小元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 MATLAB 中获取一维数组中n 个最小元素"的索引?

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

数组是一个行向量.

我可以使用 ;

[C, ind] = min(featureDist);

向量是这样的:

featureDist =

  Columns 1 through 8

   48.4766   47.3743   59.5736   59.7450   55.0489   58.2620   63.3865   50.1101

等等...

推荐答案

您可以使用排序函数.为了得到最小的 n 个元素,你可以写一个这样的函数:

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

让我们试试你的数组:

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

返回

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

这篇关于如何找到向量中 n 个最小元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆