Octave/MATLAB:使用矩阵访问矩阵中的元素,无需循环
Octave/MATLAB: Using a matrix to access elements in a matrix without loops
考虑一下,这两个矩阵:
>> columns = [1,3,2,4]
和
>> WhichSet =
[2, 2, 1, 2;
1, 1, 2, 1;
1, 2, 1, 2;
2, 1, 2, 2]
我的意图是执行以下操作:
>> result = [WhichSet(1,columns(1)), WhichSet(2,columns(2)), WhichSet(3, columns(3)) and WhichSet(4, columns(4))]
result = [2,2,2,2]
没有任何循环。
由于索引的工作原理,您不能像现在这样插入它们,除非您使用线性索引
您需要的线性指数是:
ind=sub2ind(size(WhichSet),1:size(whichSet,1),columns);
然后
out=WhichSet(ind);
考虑一下,这两个矩阵:
>> columns = [1,3,2,4]
和
>> WhichSet =
[2, 2, 1, 2;
1, 1, 2, 1;
1, 2, 1, 2;
2, 1, 2, 2]
我的意图是执行以下操作:
>> result = [WhichSet(1,columns(1)), WhichSet(2,columns(2)), WhichSet(3, columns(3)) and WhichSet(4, columns(4))]
result = [2,2,2,2]
没有任何循环。
由于索引的工作原理,您不能像现在这样插入它们,除非您使用线性索引
您需要的线性指数是:
ind=sub2ind(size(WhichSet),1:size(whichSet,1),columns);
然后
out=WhichSet(ind);