Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
假设我有以下矩阵:
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和ismember查找等于这些值的所有元素(如果存在重复值,则可能超过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 更多&回答... |
![]() |
![]() |