在MATLAB中无需for循环即可扫描每一列 [英] Scan each column without for loop in MATLAB
本文介绍了在MATLAB中无需for循环即可扫描每一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I = [2 1];
A = [7 11
8 17];
如何在没有for
循环的情况下在A中选择正确的值? I
是A
中每一列的索引向量.那是I(1) is 8
和I(2) = 11
.
How can I pick the right value in A without for
loop? I
is a vector of indices for each column in A
. That is I(1) is 8
and I(2) = 11
.
推荐答案
使用 sub2ind
生成基于右行和列坐标的线性索引,然后使用它们索引到A
.在这种情况下,I
选择右行,并且您只希望从第一列到最后一列为每个列选择一个元素:
Use sub2ind
to generate linear indices based on the right row and column coordinates, then use these to index into A
. In this case, I
chooses the right row and you want to choose only one element for each column from the first up to the last:
ind = sub2ind(size(A), I, 1:numel(I));
out = A(ind);
示例
>> I = [2 1];
>> A = [7 11
8 17];
>> ind = sub2ind(size(A), I, 1:numel(I));
>> out = A(ind);
>> out
out =
8 11
这篇关于在MATLAB中无需for循环即可扫描每一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文