PDA

查看完整版本 : 获取矩阵中n个最大元素的索引


poster
2019-12-10, 20:41
假设我有以下矩阵:

01 02 03 06 03 05 07 02 13 10 11 12 32 01 08 03 我想要前5个元素的索引(在本例中为32、13、12、11、10)。在MATLAB中最干净的方法是什么?



回答:

您可以通过多种方式来执行此操作,具体取决于您要如何处理重复值。这是一个使用sort (https://www.mathworks.com/help/matlab/ref/sort.html)查找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 (https://www.mathworks.com/help/matlab/ref/unique.html)和ismember (https://www.mathworks.com/help/matlab/ref/ismember.html)查找等于这些值的所有元素(如果存在重复值,则可能超过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

更多&回答... (https://stackoverflow.com/questions/2692482)