Multiplying Two Matrices in R

Multiplying two matrices in R

You need the transpose of the second matrix to get the result you wanted:

> v1 <- c(1,2,3)
> v2 <- matrix(c(3,1,2,2,1,3,3,2,1), ncol = 3, byrow = TRUE)
> v1 %*% t(v2)
[,1] [,2] [,3]
[1,] 11 13 10

Or potentially quicker (see ?crossprod) if the real problem is larger:

> tcrossprod(v1, v2)
[,1] [,2] [,3]
[1,] 11 13 10

Manually multiplying two matrices in R

Okay. I found the solution.

matrixMul <- function(mat1)
{
rows <- nrow(mat1)
cols <- ncol(mat1)

matOut <- matrix(nrow = rows, ncol = cols) # empty matrix

for (i in 1:rows)
{
for(j in 1:cols)
{
vec1 <- mat1[i,]
vec2 <- mat1[,j]

mult1 <- vec1 * vec2

matOut[i,j] <- sum(mult1)
}
}

return(matOut)
}

mat1 <- matrix(c(1,2,3,4), nrow = 2, ncol=2)
mult1 <- matrixMul(mat1)
mult1

Multiply two matrices with different dimensions in R

Convert yy to a vector by c() and it will be recycled to the dimension of xx when multiplying.

xx * c(yy)

# [,1] [,2] [,3]
# [1,] 10 20 30
# [2,] 400 500 600

Or by matrix multiplication :

diag(c(yy)) %*% xx

Use lapply to multiply two lists of matrices in R

In lapply, you can iterate over only one object. You may use Map here -

Map(function(x, y)  x[,-1]*y[,-1], l1, l2)

#[[1]]
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#[1,] 129 225 329 441 561 689 825 969 1121
#[2,] 176 276 384 500 624 756 896 1044 1200

#[[2]]
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#[1,] 1449 1625 1809 2001 2201 2409 2625 2849 3081
#[2,] 1536 1716 1904 2100 2304 2516 2736 2964 3200

To use lapply you may use the index to subset both l1 and l2.

lapply(seq_along(l1), function(x) l1[[x]][, -1] * l2[[x]][, -1])

Matrix Multiplication in r

You could just use apply() to multiply each column of mat1 by mat2. (The "*" will carry out R's typically vectorized element-wise multiplication of the two equal-length vectors).

apply(mat1, 2, "*", mat2)
[,1] [,2]
[1,] 0.1785476 0.4175557
[2,] 0.2644247 -0.3745997
[3,] -0.5328542 0.8945527
[4,] -2.7351502 -0.7715341
[5,] -0.9719129 -0.1346929

Or better yet, convert mat1 to a vector to take advantage of R's recycling rules:

mat2 <- matrix(1:10, ncol=2)
mat1 <- matrix(1:5, ncol=1)

as.vector(mat1)*mat2
[,1] [,2]
[1,] 1 6
[2,] 4 14
[3,] 9 24
[4,] 16 36
[5,] 25 50

An own function to multiply two matrices in r

We can try with a nested sapply

t(sapply(seq_len(ncol(m1)), function(i) 
sapply(seq_len(nrow(m2)), function(j) sum(m1[i,] * m2[,j]))))
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1590 1865 2140 2415 2690
#[2,] 1730 2030 2330 2630 2930
#[3,] 1870 2195 2520 2845 3170
#[4,] 2010 2360 2710 3060 3410
#[5,] 2150 2525 2900 3275 3650

which is similar to

  m1%*%m2
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1590 1865 2140 2415 2690
#[2,] 1730 2030 2330 2630 2930
#[3,] 1870 2195 2520 2845 3170
#[4,] 2010 2360 2710 3060 3410
#[5,] 2150 2525 2900 3275 3650

data

 m1 <- matrix(1:25, 5, 5)
m2 <- matrix(26:50, 5, 5)

Using R and Rcpp, how to multiply two matrices that are sparse Matrix::csr/csc format?

There's a reason that dgRMatrix crossproduct functions are not yet implemented, in fact, they should not be implemented because otherwise they would enable bad practice.

There are a few performance considerations when working with sparse matrices:

  • Accessing marginal views against the major marginal orientation is highly inefficient. For instance, a column iterator in a dgRMatrix and a row iterator in a dgCMatrix need to loop through almost all elements of the matrix to find the ones in just that column or row. See this Rcpp gallery post for additional enlightenment.
  • A matrix cross-product is simply a dot product between all combinations of columns. This means the penalty of using a column iterator in a dgRMatrix (vs. a column iterator in a dgCMatrix) is multiplied by the number of column combinations.
  • Cross-product functions in R are highly optimized, and are not (in my experience) significantly faster than Eigen, Armadillo, equivalent STL variants. They are parallelized, and the Matrix package takes wonderful advantage of these optimized algorithms. I have written C++ parallelized STL cross-product variants using Rcpp structures and I don't see any increase in performance.
  • If you're really going this route, check out my Rcpp gallery post on Sparse Matrix structures in Rcpp. This is to be preferred to Eigen and Armadillo Sparse Matrices if memory is a concern, as Eigen and Armadillo perform a deep copy rather than a reference to an R object already existing in memory.
  • At 1% density, the inefficiencies of row iterators will be greater than at say 5 or 10% density. I do most of my tests at 5% density and generally binary operations take 5-10x longer for row iterators than for column iterators.

There may be applications where row-major ordering shines (i.e. see the work by Dmitry Selivanov on CSR matrices and irlba svd), but this is absolutely not one of them, in fact, so much so you are better off doing in-place conversion to get to a CSC matrix.

tl;dr: column-wise cross-product in row-major matrices is the ultimatum of inefficiency.



Related Topics



Leave a reply



Submit