Lisa
Lisa

Reputation: 271

Matrix multiplication by loop in R

Two matrices A & B, with ncol = 2, nrow = 2 separetly.

A = [a_11 a_12
     a_21 a_22]

B = [b_11 b_12
     b_21 b_22]

(sorry didnt how to show matrix here...)

Multiply these 2 matrices and aim to obtain a new result matrix as:

c = [a_11*b_11 a_11*b_12 a_12*b_11 a_12*b_12
     a_21*b_21 a_21*b_22 a_22*b_21 a_22*b_22] 

Obviously, it could be done with some loop, but I'd assume there exist simpler methods

C <- matrix(NA, nrow = nrow(A), ncol = ncol(A)*ncol(B))
for (m in 1 : nrow(C)) {
    for (k in 1:ncol(A)) { 
        C[m, (ncol(B)*(k-1)+1) : (k*ncol(B))] <- d1[m, k] * d2[m,]
    }
}

Upvotes: 0

Views: 636

Answers (1)

jogo
jogo

Reputation: 12569

You can do:

cbind(A[, 1]*B, A[,2]*B) # or 
matrix(apply(A, 2, function(x) x*B), 2)

data

A <- matrix(1:4, 2)
B <- matrix(11:14, 2)

Upvotes: 1

Related Questions