user4688329
user4688329

Reputation:

R error on matrix multiplication: non-conformable arguments

I have an R loop that has been giving me error. Here are the dimensions of the matrices..

      > dim(A)
     [1] 2 2
     > dim(backward)
     [1] 6848    2

I am trying to run this loop and get the following error:

      for (i in t:1){
      backward[i,]=A%*%t(backward[i,])}
      Error in A %*% t(backward[i, ]) : non-conformable arguments

Where t equals 6848. Thanks for your time.

EDIT with bgoldst code:

           > A
          [,1] [,2]
        [1,]  0.8  0.2
        [2,]  0.2  0.8
        > backward <- matrix(1:(t*2),t,2);
        >   dim(backward)
       [1] 6848    2
       > for (i in t:1) backward[i,] <- A%*%t(backward[i,,drop=F]);
       Error in A %*% t(backward[i, , drop = F]) : non-conformable arguments

Upvotes: 2

Views: 11381

Answers (1)

bgoldst
bgoldst

Reputation: 35324

I'm guessing that your expectation of

backward[i,]

is that it will return a 1x2 matrix, which you would be able to use as the operand of a matrix multiplication. This is incorrect. In R, when you specify a single index within a dimension of a matrix, then by default, R will "drop" that dimension. In the case of the above piece of code, the row dimension is dropped, and you end up with a vector, whose contents are taken from all columns along the indexed row. A vector is not a valid operand to a matrix multiplication.

You can solve this problem by providing the drop argument to the [ operation:

A <- matrix(1:(2*2),2,2);
backward <- matrix(1:(6848*2),6848,2);
t <- nrow(backward); for (i in t:1) backward[i,] <- A%*%t(backward[i,,drop=F]); ## no error

Here's a demo of the effect of drop=F:

backward[1,]
## [1] 20548 27398
backward[1,,drop=F]
##       [,1]  [,2]
## [1,] 20548 27398

See ?`[` for more info.


Here's a solution that doesn't depend on the drop=F argument:

for (i in t:1) backward[i,] <- A%*%t(matrix(backward[i,],1));

Upvotes: 4

Related Questions