Search code examples
rmatrixmatrix-multiplicationdimensions

Dimensions of matrix multiplication


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!


Solution

  • 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.