Search code examples
rfunctionmatrixmatrix-multiplication

How do I adjust my function to multiply multiple (random number of) matrices?


I have written the following function for multiplying two matrices A and B:

f <- function(A,B){
       m<-nrow(A)
       n<-ncol(A)
       n<-nrow(B)
       p<-ncol(B)
       Result<-matrix(0,nrow = m,ncol = p)
       for(i in 1:m){
         for(j in 1:p){
           for(k in 1:n){
             Result[i,j]<-Result[i,j]+A[i,k]*B[k,j]  
             }
           }
         }
       return(Result)
       }

How would I adjust my function code to multiple 3 or more, i.e., a random number of matrices rather than just 2?


Solution

  • You just iteratively apply two-matrix multiplication. Let f be the fundamental function multiplying two matrices A and B. Normally we use the internal one %*%, but you can use the one defined in your question.

    Since the number of matrices are unknown, I suggest using .... We collect all matrices input into a "matrix list" by list(...), then use Reduce to cumulatively apply two-operand matrix multiplication.

    g <- function (...) Reduce(f, list(...))
    

    Note, it is your responsibility to ensure the matrix dimension are conformable, especially when you have a lot of matrices. In the following, I would just use square matrices as an example.

    set.seed(0)
    A <- matrix(rnorm(4),2)
    B <- matrix(rnorm(4),2)
    C <- matrix(rnorm(4),2)
    f <- "%*%"
    
    g(A, B, C)
    #          [,1]        [,2]
    #[1,] -3.753667  0.08634328
    #[2,] -0.161250 -1.54194176
    

    And this is as same as:

    A %*% B %*% C
    #          [,1]        [,2]
    #[1,] -3.753667  0.08634328
    #[2,] -0.161250 -1.54194176