0
是否可以使用矩阵条目作为其他矩阵的索引? 例如:使用2Xn矩阵条目作为索引
A=[1 2 ; 4 5 ; 6 7 ];
我想达到使用A等矩阵的条目,而不使用循环。
Othermat(1,2), Othermat(4,5) %...
如果是我该怎么办?
是否可以使用矩阵条目作为其他矩阵的索引? 例如:使用2Xn矩阵条目作为索引
A=[1 2 ; 4 5 ; 6 7 ];
我想达到使用A等矩阵的条目,而不使用循环。
Othermat(1,2), Othermat(4,5) %...
如果是我该怎么办?
当然,使用sub2ind
:
A = [1 2; 4 5; 6 7];
ind = sub2ind(size(Othermat),A(:,1),A(:,2));
values = Othermat(ind);
建议的sub2ind
是生成指数的自然方式。
当然这也不是很难找到直接的线性指标:
A = [1 2; 4 5; 6 7];
Othermat = magic(7);
Othermat(A(:,1)+(A(:,2)-1)*size(Othermat,1))