查看单个帖子
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 获取矩阵中n个最大元素的索引

假设我有以下矩阵:

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个最大的唯一值,然后使用uniqueismember查找等于这些值的所有元素(如果存在重复值,则可能超过5个):

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

更多&回答...
poster 当前离线   回复时引用此帖