Search code examples
rfor-loopapplymatrix-multiplication

How to multiply parts of matrices?


I will be extremely brief! Here is a little reproducible example:

Z1 <- matrix(rep(c(1, 0, 0, 0, 0,
                   1, 1, 0, 0, 0,
                   1, 0, 1, 0, 0,
                   1, 0, 0, 1, 0,
                   1, 0, 0, 0, 1),
                 times = 3),
               nrow  = 15,
               ncol  = 5,
               byrow = TRUE)

z <- matrix(c(0.1, 0.2, 0.3, 0.4, 0.5,
              0.6, 0.7, 0.8, 0.9,   1,
                1,   2,   3,   4,   5),
            nrow  = 3,
            ncol  = 5,
            byrow = TRUE)

I need a scalable non for-loop solution (e. g. involving something from the apply-family) which gives an equivalent result to these calculations I will now perform by hand:

Zz1 <- Z1[1:5,]   %*% z[1,]
Zz2 <- Z1[6:10,]  %*% z[2,]
Zz3 <- Z1[11:15,] %*% z[3,]
Zz  <- rbind(Zz1, Zz2, Zz3)

Solution

  • Very similar to a question from earlier today:

    rowSums(Z1 * z[rep(1:3,each=5),])
    #[1] 0.1 0.3 0.4 0.5 0.6 0.6 1.3 1.4 1.5 1.6 1.0 3.0 4.0 5.0 6.0