r - Is it possible to apply outer on A and B which are both matrices, and a function which takes 2 vectors and returns a scalar? -
i wish use like:
outer(a,b,myfun)
to achieve like:
a<-matrix(nrow=nrow(a),ncol=nrow(b)) for(i in 1:nrow(a)) (j in 1:nrow(b)) { a[i,j]<-myfun(a[i,],b[j,]) }
is there better way?
cannot give general answer since details of how myfun
may affect answer.
ares <- expand.grid(1:nrow(a), 1:nrow(b)) ares$res <- myfun(a[ares[,1], ), b[res[,2] ) # may need mapply("myfun", a[ares[,1], ), b[res[,2] ) on vectorize based # or do.call(my.fun, ....) <- matrix(ares$res, nrow(a), nrow(b) )
Comments
Post a Comment