1

I am running a for loop with matrices. One line does not work properly:

K[1:2,i] * FF[i] %*% K1[i,1:2]

K is a 2 by n matrix, where i updates in the for loop. FF is an array(1:n) and K1 is the transpose of K. Taken out of the for loop, with the initial values:

n <- 100
K <- matrix(c(2,1), nrow=2, ncol=n)
K1 = t(K)
FF <- array(1:n)
FF[1] <- 10^7
K[1:2,1] * FF[1] %*% K1[1,1:2]

the result that R gives me is a 1 * 2 matrix. It should be a 2 * 2 matrix.

I have tried to exclude FF, but also then the matrix dimensions are not correct.

Thanks for helping!

kf99
  • 23
  • 4
  • 2
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jun 09 '22 at 15:36
  • 1
    I can't reproduce the issue. If I define `K = matrix(1:4, nrow = 2)` and `FF = 5`, then `K[1:2, 1] * FF %*% K[1, 1:2]` works just fine. Please update your question with sample inputs for the small test case. – Gregor Thomas Jun 09 '22 at 15:38
  • @MrFlick and Gregor Thomas, I edited the post. Let me know if more is needed! – kf99 Jun 09 '22 at 15:56

1 Answers1

2

You have 2 problems. One is that R eagerly converts single-column matrices to vectors, so K[1:2,1] is interpreted as a vector, not a matrix. We can fix this with the drop = FALSE argument to [.

There's also an order-of-operations problem, %*% has higher precedence than *, so we need parentheses to make the * happen first:

(K[1:2, 1, drop = F] * FF[1]) %*% K1[1, 1:2]
#       [,1]  [,2]
# [1,] 4e+07 2e+07
# [2,] 2e+07 1e+07

Unrelated to your problem, but it seems strange to make FF an array, seems like a length-100 vector would be simpler.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294