获取矩阵中n个最大元素的索引

编程入门 行业动态 更新时间:2024-10-07 12:18:33
本文介绍了获取矩阵中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 和 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个最大元素的索引

本文发布于:2023-11-30 07:36:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   索引   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!