Adrian
Adrian

Reputation: 843

Looping a matrix - vector multiplication, whose elements change with every loop

I have a dataset with very large matrices and vectors. I would like to multiply a matrix with a vector that has one "1" element with the rest being zero. I would like to loop this calculation so that every possible 1 and 0 combination within the vector has been multiplied with the matrix, and the store the results in a vector.

I give an example of what I'm trying to do.

I have two matrices, a and b:

a <- matrix(1:16, nrow = 4, byrow = TRUE)
b <- matrix(17:32, nrow = 4, byrow = TRUE)

and a vector with 1's and 0's. As I don't know how to loop well yet, I write down the code for each combination:

c1 <- rep(0, times = 4)
c1[1] <- 1
c2 <- rep(0, times = 4)
c2[2] <- 1
c3 <- rep(0, times = 4)
c3[3] <- 1
c4 <- rep(0, times = 4)
c4[4] <- 1

I multiply a with each of the vector combinations c, diagonalize it, multiply this with b and sum each row and column. I then store this result in a vector results:

d1 <- sum(colSums(b %*% diag(as.vector(a %*% c1), nrow = 4)))
d2 <- sum(colSums(b %*% diag(as.vector(a %*% c2), nrow = 4)))
d3 <- sum(colSums(b %*% diag(as.vector(a %*% c3), nrow = 4)))
d4 <- sum(colSums(b %*% diag(as.vector(a %*% c4), nrow = 4)))

results <- cbind(d1, d2, d3, d4)

that gives:

       d1   d2   d3   d4
[1,] 2824 3216 3608 4000

Is there a good line of code that does this more efficiently than what I did here?

Upvotes: 1

Views: 379

Answers (1)

jogo
jogo

Reputation: 12559

Because of the special structure of your calculation you can shorten it to

a <- matrix(1:16, nrow = 4, byrow = TRUE)
b <- matrix(17:32, nrow = 4, byrow = TRUE)

results <- apply(a, 2, function(ai) sum(b %*% ai))
# [1] 2824 3216 3608 4000

or even shorter

colSums(b %*% a)
# [1] 2824 3216 3608 4000

Upvotes: 1

Related Questions