假设我们有以下内容:
x <- matrix(1:9, nrow=3)
y <- c(1,2,3)
x%*%y
y%*%x
为什么矩阵乘法不是未定义的?我们知道这x
是一个 3 x 3 矩阵并且y
是一个 1 x 3 矩阵。所以x %*% y
不应该被定义,y %*% x
应该是一个 1 x 3 的矩阵。
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