Reputation:
Suppose we have the following:
x <- matrix(1:9, nrow=3)
y <- c(1,2,3)
x%*%y
y%*%x
Why are the matrix multiplications not undefined? We know that x
is a 3 x 3 matrix and y
is a 1 x 3 matrix. So x %*% y
should not be defined and y %*% x
should be a 1 x 3 matrix.
Upvotes: 5
Views: 3553
Reputation: 1510
Luckily (or unfortunately, depending on the situation) many R operators (in their default state) are overloaded and do all sorts of things 'under the hood' - in this example, the default functionality for %*%
in R
automatically coerces y
to matrix whose dimension will work. When you type
x %*% y
it makes y
a 3 x 1 matrix and when you type
y %*% x
it makes y
a 1 x 3 matrix.
Try comparing those with when you type
x %*% as.matrix(y)
and
t(as.matrix(y)) %*% x
respectively
Upvotes: 7