matlab - 满足特定标准的最小值的 MATLAB 索引
问题描述
说我有一个矩阵
A= [1 2 3
2 5 5
4 6 2]
我想从特定范围的列中找到最大值的索引,由向量给出,A_index =[1 0 1]
意思是从第 1 列和第 3 列中找到最大值。这个最大值是 5 。如何找到它的索引,即行 = 2 列 = 3。请注意,5 也出现在第 2 列中,但我不想要它如果我使用普通的 " find
",我没有得到正确的解决方案
解决方案
用 替换不需要的列的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(:)));
无论你觉得哪个更好。
推荐阅读
- cluster-analysis - 根据多个字符串相似度评级对字符串进行聚类
- r - 为什么在 R 中使用 SMOTE 时会出现“T[, col] <- data[, col] 中的错误”?
- python - 第 18 章:Python 自动 GUI
- android - 警报对话框不会显示在我的 onSwipe 方法中
- angular - 角度引导日期选择器不调用函数
- javascript - Laravel 6 带删除的多文件预览
- android-studio - android studio更新补丁在哪里下载的?
- python - 从文件 md5 和文件名中生成一致的 uuid,如哈希
- reactjs - 将 UI 组件双向绑定到可观察对象以减少渲染的最佳方法是什么?
- flutter - Flutter:如何将容器的高度调整为其连续兄弟的最大高度