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

编程入门 行业动态 更新时间:2024-10-27 05:23:21
本文介绍了获取矩阵中 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?

推荐答案

根据您希望如何处理重复值,有几种方法可以做到这一点.这是一个使用 排序:

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 个最大元素的索引

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

发布评论

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

>www.elefans.com

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