peter.petrov
peter.petrov

Reputation: 39477

R - matrix multiplication - no error signaled

> x <- c(1,1) 
> m <- rbind(c(1,4),c(2,2))  
> m %*% x   # 1 
     [,1]
[1,]    5
[2,]    4
> x %*% m   # 2  
     [,1] [,2]
[1,]    3    6
> 

I can understand how and why the second multiplication works. In math a 1x2 (1 row, 2 columns) matrix can be multiplied by a 2x2 matrix.

But why does the first one work and why does it produce no error or warning at all? In math a 2x2 matrix cannot be multiplied by a 1x2 vector/matrix.

Note that if I initialize x like this below, and if I then multiply m to x, I get the same result as in the first example above.

> x <- cbind(c(1,1));
> x
     [,1]
[1,]    1
[2,]    1
> m %*% x   #  3  
     [,1]
[1,]    5
[2,]    4

So I think that this third example is the right way to do it.
Then why is the first example working OK without error or warning?

Upvotes: 4

Views: 301

Answers (1)

J.R.
J.R.

Reputation: 3888

Directly from the documentation, ?matmult:

matmult {base}

Multiplies two matrices, if they are conformable. If one argument is a vector, it will be promoted to either a row or column matrix to make the two arguments conformable. If both are vectors of the same length, it will return the inner product (as a matrix).

So the following amounts to the same thing (ignoring attributes):

x %*% m
t(x) %*% m 
rbind(x) %*% m 

and in the same way:

m %*% x
m %*% t(t(x))
m %*% cbind(x)

but m %*% t(x) or t(t(x)) %*% m will give you an error, because t() will return a matrix and the dimensions are now incompatible. This also illustrates, that the vector is better interpreted as a column- than a row-vector.

Upvotes: 1

Related Questions