【问题标题】:How to find the index of the n smallest elements in a vector如何找到向量中 n 个最小元素的索引
【发布时间】:2012-12-17 22:10:12
【问题描述】:

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

数组是一个行向量。

我可以使用 ; 找到最小的元素及其索引

[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

等等……

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您可以使用sort 函数。要获取最小的 n 个元素,可以编写如下函数:

    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
    

    【讨论】:

      【解决方案2】:

      我知道这是一个非常晚的回复,但我希望能帮助以后可能有这个问题的任何人。

      如果A是元素数组,yu可以尝试使用find函数来确定n个最小元素的索引。

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

      要确定n个最大的元素,

      [~, idx] = find(A

      【讨论】:

      • 我认为这行不通。您的代码返回向量中的第一个/最后一个“n”元素,而不是根据需要返回最小/最大的“n”个元素
      猜你喜欢
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多