Matlab在列中找到x min值的索引

时间:2014-09-27 15:08:55

标签: arrays matlab min

我在Matlab中有任何构建函数可以在x(参数)min值的列索引中找到吗?

例如:

a = [1; 2; 3; 4; 0; 5]
someFindFunction(a, 2)
ans = [5, 1]
someFindFunction(a, 1)
ans = [5]
someFindFunction(a, 3)
ans = [5, 1, 2]

2 个答案:

答案 0 :(得分:3)

如果你不介意全部完成,那么[~, ans] = sort(a)就可以了。然后,您可以获取实际需要的ans的前几个元素。 sort中的构建速度极快,尽管找到了所有分钟而不仅仅是你需要的分钟,但这应该足够高效。

答案 1 :(得分:1)

@NirFriedman确实回答了你的问题,但这是一个更加独立的答案。带有第二个输出参数的sort会告诉您其中在对它们进行排序后,每个值都会出现在原始矩阵中。因此,如果您想将所要求的内容输入函数,则可以使用第二个参数索引到第二个输出,并且仅从第一个元素生成这些值,直到您想要的数量。我们也称之为“someFindFunction而不是findSmallestLocations,而不是function [out] = findSmallestLocations(a, ind) %// Sort the values and get where they're located [~,b] = sort(a); %// Retrieve the locations that you want from 1 up to ind out = b(1:ind); end 。就这样:

findSmallestLocations.m

这应该可以产生你想要的东西。如果您想自己运行,请将上述代码复制并粘贴到名为>> a = [1; 2; 3; 4; 0; 5] >> findSmallestLocations(a, 2) ans = 5 1 >> findSmallestLocations(a, 1) ans = 5 >> findSmallestLocations(a, 3) ans = 5 1 2 的M文件中,然后将当前工作目录设置为此文件所在的位置,以便您可以调用此函数。

使用您的示例输入和预期输出,这就是我们得到的:

{{1}}
相关问题