matrix - Use values from 2 matrices to index a third in R -


i'm optimizing more complex code, got stuck problem.

a<-array(sample(c(1:10),100,replace=true),c(10,10))   m<-array(sample(c(1:10),100,replace=true),c(10,10))   f<-array(sample(c(1:10),100,replace=true),c(10,10))   g<-array(na,c(10,10))  

i need use values in & m index f , assign value f g
i.e. g[1,1]<-f[a[1,1],m[1,1]] except indexes, , optimally/fast possible

i make loop me seems rather dumb , slow. seems should able in apply family, i've had no luck figuring out how that. need keep data structured here can use matrix operations in different parts of code. i've been searching answer haven't found particularly helpful yet.

g[] <- f[cbind(c(a), c(m))] 

this takes advantage of fact matrices can addressed vectors , using matrix index.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -