简体   繁体   中英

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,]
    }
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM