[英]Octave/MATLAB: Using a matrix to access elements in a matrix without loops
Consider, the two matrices: 考虑以下两个矩阵:
>> columns = [1,3,2,4]
and 和
>> WhichSet =
[2, 2, 1, 2;
1, 1, 2, 1;
1, 2, 1, 2;
2, 1, 2, 2]
My intent is to do the following : 我的意图是执行以下操作 :
>> result = [WhichSet(1,columns(1)), WhichSet(2,columns(2)), WhichSet(3, columns(3)) and WhichSet(4, columns(4))]
result = [2,2,2,2]
without any loops. 没有任何循环。
Because how indexing works, you can not just plug them as they are now, unless you use linear indexing 由于索引的工作方式,除非您使用线性索引 ,否则您不能只是像现在那样插入它们
Your desired linear indices are: 您需要的线性指数为:
ind=sub2ind(size(WhichSet),1:size(whichSet,1),columns);
Then 然后
out=WhichSet(ind);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.