假设我有一个矩阵
A= [1 2 3
2 5 5
4 6 2]我想从特定的列范围中找到最大值的索引,这是由向量A_index =[1 0 1]给出的,意思是从列1和3中找到最大值,这个最大值是5。如何找到它的索引,即行=2列= 3。注意,5也出现在第2列中,但我不想要它,如果我使用普通的"find“,我没有得到正确的解决方案。
发布于 2019-05-16 19:17:42
将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(:)));不管你找到什么更好的。
https://stackoverflow.com/questions/56175058
复制相似问题