简体   繁体   English

使用2Xn矩阵条目作为索引

[英]use 2Xn matrix entries as indices

Is it possible to use matrix entries as indices to other matrix ? 是否可以使用矩阵条目作为其他矩阵的索引? for example : 例如 :

A=[1 2 ; 4 5 ; 6 7 ];

And I want to reach entries of other matrix using A, without using loops. 我想使用A而不使用循环来访问其他矩阵的条目。

Othermat(1,2), Othermat(4,5) %...

If yes how can I do it ?! 如果是,我该怎么办?

Sure, use sub2ind : 当然,请使用sub2ind

A = [1 2; 4 5; 6 7];
ind = sub2ind(size(Othermat),A(:,1),A(:,2));
values = Othermat(ind);

The suggested sub2ind is a natural way to generate indices. 建议的sub2ind是生成索引的自然方法。

Of course it is also not very hard to find the linear index directly: 当然直接找到线性索引也不是很困难:

A = [1 2; 4 5; 6 7];
Othermat = magic(7);

Othermat(A(:,1)+(A(:,2)-1)*size(Othermat,1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM