Search code examples
ralgorithmmatrixmatrix-multiplication

Algorithm for matrix multiplication


I am required to write a one-loop algorithm for matrix multiplication without using %*%, with the help of colSums().

I have tried working through matrix multiplication traits, but failed to find a pattern which can be attained with colSums().


Solution

  • If you are NOT ALLOWED to use %*% and HAVE TO take colSums anyway, you can try

    matrix(
        colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]), 
        nrow(a),
        byrow = TRUE
    )
    

    Example: Given two matrices a and b like below

    > set.seed(0)
    
    > (a <- matrix(runif(12), 3))
              [,1]      [,2]      [,3]       [,4]
    [1,] 0.8966972 0.5728534 0.8983897 0.62911404
    [2,] 0.2655087 0.9082078 0.9446753 0.06178627
    [3,] 0.3721239 0.2016819 0.6607978 0.20597457
    
    > (b <- matrix(rnorm(8), 4))
                 [,1]       [,2]
    [1,] -0.928567035  0.7635935
    [2,] -0.294720447 -0.7990092
    [3,] -0.005767173 -1.1476570
    [4,]  2.404653389 -0.2894616
    

    we have

    > a %*% b
                [,1]       [,2]
    [1,]  0.50614499 -0.9861506
    [2,] -0.37108354 -1.6249737
    [3,]  0.08650475 -0.6949853
    
    > matrix(
    +     colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]),
    +     nrow(a),
    +     byrow = TRUE
    + )
                [,1]       [,2]
    [1,]  0.50614499 -0.9861506
    [2,] -0.37108354 -1.6249737
    [3,]  0.08650475 -0.6949853