Multiplying each column of a matrix with row of another matrix for square matrices of dimension 20

I have two square matrices mat1 and mat2 of dimension 20 and I want to multiply a column of each matrix with a row of the other matrix and save the resultant matrices in a list. So multiply column1 of mat1 with row1 of mat2 and save it as a matrix, then multiply column 2 of mat1 with row2 of mat2 and save it as a matrix and so on. I have tried this for a 3x3 matrix and providing an example below. I think I will have to write a loop for a higher dimension square matrix like 20x20 but not sure how to do it.

mat1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow=3, byrow=TRUE)
mat2 <- matrix(c(10,11,12,13,14,15,16,17,18), nrow=3, byrow=TRUE)
mydata <- list()
mydata[[1]] <- matrix(mat1[,1])%*%t(matrix(mat2[1,]))
mydata[[2]] <- matrix(mat1[,2])%*%t(matrix(mat2[2,]))
mydata[[3]] <- matrix(mat1[,3])%*%t(matrix(mat2[3,]))
mydata
#> [[1]]
#>      [,1] [,2] [,3]
#> [1,]   10   11   12
#> [2,]   40   44   48
#> [3,]   70   77   84
#> 
#> [[2]]
#>      [,1] [,2] [,3]
#> [1,]   26   28   30
#> [2,]   65   70   75
#> [3,]  104  112  120
#> 
#> [[3]]
#>      [,1] [,2] [,3]
#> [1,]   48   51   54
#> [2,]   96  102  108
#> [3,]  144  153  162

I need help with doing the same exercise for mat1 and mat2 with a 20x20 dimension. If someone could help me with how to write a loop, I would really appreciate that. Thanks!

no explicit loops required.

mat1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow=3, byrow=TRUE)
mat2 <- matrix(c(10,11,12,13,14,15,16,17,18), nrow=3, byrow=TRUE)
mydata1 <- list()
mydata1[[1]] <- matrix(mat1[,1])%*%t(matrix(mat2[1,]))
mydata1[[2]] <- matrix(mat1[,2])%*%t(matrix(mat2[2,]))
mydata1[[3]] <- matrix(mat1[,3])%*%t(matrix(mat2[3,]))
mydata1

library(purrr)
mydata2 <- purrr::map(seq_len(nrow(mat1))
           ,~matrix(mat1[,.x])%*%t(matrix(mat2[.x,])))

all.equal(mydata1,mydata2)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.