首页 > 解决方案 > 满足特定标准的最小值的 MATLAB 索引

问题描述

说我有一个矩阵

A= [1 2 3
    2 5 5
    4 6 2]

我想从特定范围的列中找到最大值的索引,由向量给出,A_index =[1 0 1]意思是从第 1 列和第 3 列中找到最大值。这个最大值是 5 。如何找到它的索引,即行 = 2 列 = 3。请注意,5 也出现在第 2 列中,但我不想要它如果我使用普通的 " find",我没有得到正确的解决方案

标签: matlab

解决方案


用 替换不需要的列的A元素NaN。然后用于max查找最大元素的线性索引。最后使用 . 将线性索引转换为行和列下标ind2sub

A_index(A_index==0)=NaN; %Replacing 0s with NaNs (needed when A has non-positive elements)
A = bsxfun(@times, A, A_index); %With this, zeros (now NaNs) of A won't affect 'max'
[~ , ind] = max(A(:));          %finding the linear index of the maximum value
[r, c] = ind2sub(size(A),ind);  %converting the linear index to row and column subscripts

在≥ R2016b 中,第二行可以用隐式展开写成:

A = A.*A_index;

最后两行也可以写成:

[r,c] = find(A==max(A(:)));

无论你觉得哪个更好。


推荐阅读