In R it's possible to perform a cross-product by using %*% between two matrices M1: n x p and M2: p x d, that is having one dimension length in common.
To do the cross-product one multiplies for each row 1..n in M1 and column 1..d in M2 the relative p_M1 x p_M2 and then sums the resulting vector.
But instead of the sum I would like to have the product prod(p_M1 x p_M2).
I can do this with nested loops in R, but it's very slow and my matrices are very big. Is there an alternative as fast as %*%?
EXAMPLE:
set.seed(1)
a <- matrix(sample((1:100) / 100, 15), ncol = 3)
b <- matrix(sample((1:100) / 100, 15), ncol = 5)
# This produces the usual cross-product...
a %*% b
# ...which can be done also using loops
do.call('cbind', lapply(1:5, function(i) {
sapply(1:5, function(j) {
sum(a[i,] * b[,j])
})
}))
# But I need to do the product of the paired vectors instead of the sum. I could use a nested loop but it takes hours.
do.call('cbind', lapply(1:5, function(i) {
sapply(1:5, function(j) {
prod(a[i,] * b[,j])
})
}))