获取矩阵中 n 个最大元素的索引 [英] Get the indices of the n largest elements in a matrix
问题描述
假设我有以下矩阵:
01 02 03 06
03 05 07 02
13 10 11 12
32 01 08 03
我想要前 5 个元素的索引(在本例中为 32、13、12、11、10).在 MATLAB 中执行此操作的最简洁方法是什么?
And I want the indices of the top 5 elements (in this case, 32, 13, 12, 11, 10). What is the cleanest way to do this in MATLAB?
推荐答案
根据您希望如何处理重复值,有几种方法可以做到这一点.这是一个使用 排序
:
There are a couple ways you can do this depending on how you want to deal with repeated values. Here's a solution that finds indices for the 5 largest values (which could include repeated values) using sort
:
[~, sortIndex] = sort(A(:), 'descend'); % Sort the values in descending order
maxIndex = sortIndex(1:5); % Get a linear index into A of the 5 largest values
这里有一个解决方案,它找到 5 个最大的 unique 值,然后找到等于这些值的 所有 元素(如果有重复值,则可能超过 5 个),使用 unique
和 ismember
:
Here's a solution that finds the 5 largest unique values, then finds all elements equal to those values (which could be more than 5 if there are repeated values), using unique
and ismember
:
sortedValues = unique(A(:)); % Unique sorted values
maxValues = sortedValues(end-4:end); % Get the 5 largest values
maxIndex = ismember(A, maxValues); % Get a logical index of all values
% equal to the 5 largest values
这篇关于获取矩阵中 n 个最大元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!