简体   繁体   中英

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.

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

If yes how can I do it ?!

Sure, use 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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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