Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Vectorized" matrix multiplication

Suppose I have two matrices x and y, both with dimensions 100x2. I would like to create a list such that for each row of x and y, I have the matrix t(x) %*% y. For example, via a for loop:

x = matrix(rnorm(10), nrow = 5)
y = matrix(rnorm(10), nrow = 5)
myList = list()
for(i in 1:5){
    myList[[i]] = t(x[i, , drop = FALSE]) %*% y[i, ]
}

Is there a more efficient way to do this calculation? I've tried to figure out how to express this a matrix multiplication but have had no luck. I've also considered mapply, but it seems as if I'd need to convert x and y to lists of vectors instead of matrices to use mapply, and I'm skeptical that that is the correct approach either.

like image 755
random_forest_fanatic Avatar asked Jul 18 '26 05:07

random_forest_fanatic


1 Answers

One way with Map

Map(function(x,y) matrix(x,ncol=1)%*%y ,
               split(x, row(x)), split(y, row(y))) 
like image 92
akrun Avatar answered Jul 20 '26 20:07

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!