![]() |
获取矩阵中n个最大元素的索引
假设我有以下矩阵:
01 02 03 06 03 05 07 02 13 10 11 12 32 01 08 03 我想要前5个元素的索引(在本例中为32、13、12、11、10)。在MATLAB中最干净的方法是什么? [B]回答:[/B] 您可以通过多种方式来执行此操作,具体取决于您要如何处理重复值。这是一个使用[URL="https://www.mathworks.com/help/matlab/ref/sort.html"]sort[/URL]查找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个最大的[I]唯一[/I]值,然后使用[URL="https://www.mathworks.com/help/matlab/ref/unique.html"]unique[/URL]和[URL="https://www.mathworks.com/help/matlab/ref/ismember.html"]ismember[/URL]查找等于这些值的[I]所有[/I]元素(如果存在重复值,则可能超过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 [url=https://stackoverflow.com/questions/2692482]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 08:54。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.