简体   繁体   中英

a for loop in r with matrices

I am new to R and I have been all over stackoverflow and I couldn't find answer to my simple question.

I have a list of matrices, A,B,C... of dimension mxm and a single vector, V of dimension mx 1 I want to first multiply matrix 'A' by X, and use the resulting vector to multiply the next matrix in the list, I want something like this

m1 = A x V
m2 = B x m1
m3 = C x m2
...

I have 89 matrices to go through, manual is not an option, as I need to update number of matrices a number of times, is there a simple for loop kind of technique to make my life simpler?

Here's solution where you loop through all the matrices and store multiplication result in resultMatrix list.

m1 = A x V step is done with origMatrix[[i]] %*% myVector where i = 1
m2 = B x m1 step (and all the rest) is done with origMatrix[[i]] %*% resultMatrix[[i - 1]]

# Generate data
origMatrix <- list(matrix(rnorm(9), 3),
                   matrix(rnorm(9), 3),
                   matrix(rnorm(9), 3))

myVector <- 1:3

# Loop trough original matrices    
resultMatrix <- list()
for (i in 1:length(origMatrix)) {
    if (i == 1) {
        # Multiple first matrix by vector
        resultMatrix[[i]] <- origMatrix[[i]] %*% myVector 
    } else {
        # Multiple matrix by previous result matrix
        resultMatrix[[i]] <- origMatrix[[i]] %*% resultMatrix[[i - 1]]
    }
}

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