简体   繁体   中英

r: %*% and lapply/mapply when arguments are reversed

I have been wondering the most efficient way to do matrix multiplication on lists.

Let's say I have a matrix A and a list of matrices B :

A = matrix(c(1,2,3,4), ncol=2, nrow=2)
B = list(matrix(c(1,2,3,4), ncol=2, nrow=2), matrix(c(4,3,2,1), ncol=2, nrow=2))

And I want the list of crossproducts of A and each element b of B :

A %*% b

I was trying to use lapply() but couldn't figure out how to ensure the right sequence of multiplication without extra nested lapply 's to transpose each b ...

lapply(B, '%*%', A) # which gives a list of b%*%A rather than A%*%b
lapply(lapply(lapply(B, t), '%*%', t(A)), t) # gives the answer but geez...

Could anyone kindly give me some pointers here?

只需在lapply()定义function ,就像这样

lapply(B, function(x) A%*%x)

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