5

假设我们有以下内容:

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 的矩阵。

4

1 回答 1

7

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

于 2013-01-04T14:30:32.173 回答