假设我有以下矩阵:
01 02 03 06
03 05 07 02
13 10 11 12
32 01 08 03
我想要前 5 个元素的索引(在本例中为 32、13、12、11、10)。在 MATLAB 中执行此操作的最简洁方法是什么?
最佳答案
根据您希望如何处理重复值,有几种方法可以做到这一点。这是一个使用 sort
查找 5 个最大值(可能包括重复值)的索引的解决方案:
[~, 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
:
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
关于matlab - 获取矩阵中 n 个最大元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2692482/