获取矩阵中n个最大元素的索引 [英] Get the indices of the n largest elements in a matrix

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

问题描述

假设我有以下矩阵:

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?

推荐答案

有两种方法可以执行此操作,具体取决于您要如何处理重复值.这是一个使用 sort :

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 值,然后找到等于这些值的 all 元素(如果有重复的值,则可能超过5个),使用 unique

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屋!

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