R中的矩阵和向量乘法运算

hxd*_*011 1 r vector matrix matrix-multiplication

我觉得R中的矩阵运算非常令人困惑:我们正在混合行向量和列向量。

  • 在这里,我们定义x1为向量(我假设R默认向量是列向量吗?但它没有显示它是以这种方式排列的。)

  • 然后我们定义x2的转置x1,这对我来说也很奇怪。

  • 最后,如果我们定义x3为矩阵,则显示效果会更好。

现在,我的问题是,x1x2是完全不同的东西(一个是另一个转),但我们这里有同样的结果。

有什么解释吗?可能我不应该将向量和矩阵运算混合在一起吗?

x1 = c(1:3)
x2 = t(x1)
x3 = matrix(c(1:3), ncol = 1)

x1
[1] 1 2 3

x2
     [,1] [,2] [,3]
[1,]    1    2    3

x3
     [,1]
[1,]    1
[2,]    2
[3,]    3

x3 %*% x1
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    4    6
[3,]    3    6    9

x3 %*% x2
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    4    6
[3,]    3    6    9
Run Code Online (Sandbox Code Playgroud)

Wei*_*ong 5

?`%*%`

描述:

 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).
Run Code Online (Sandbox Code Playgroud)

  • 另请注意:R专门不将向量作为行向量或列向量处理,可以通过注意到`dim(x)== NULL`和`dim(t(x))== c(1, 3)`。如果用户认为R定义行向量,则会产生误解,因为“ c()”似乎是“连续”定义的。但是,从某种意义上说,R定义与数学定义匹配,在使用矩阵时,除符号约定外,也不必将向量声明为行向量或列向量。 (3认同)

42-*_*42- 5

长度为 3 的数值向量不是“列向量”,因为它没有维度。然而,它确实被 %*% 处理,就好像它是一个维度为 1 x 3 的矩阵一样,因为它成功了:

 x <- 1:3
 A <- matrix(1:12, 3)
 x %*% A
#------------------
     [,1] [,2] [,3] [,4]
[1,]   14   32   50   68
#----also----
 crossprod(x,A)   # which is actually t(x) %*% A (surprisingly successful)

     [,1] [,2] [,3] [,4]
[1,]   14   32   50   68
Run Code Online (Sandbox Code Playgroud)

而这并不:

 A %*% x
#Error in A %*% x : non-conformable arguments
Run Code Online (Sandbox Code Playgroud)

将原子向量与维度为 nx 1 的矩阵同等对待是有意义的,因为 R 使用列主索引处理其矩阵运算。R 结合性规则从左到右进行,所以这也成功:

  y <- 1:4
 x %*% A %*% y
#--------------    
 [,1]
[1,]  500
Run Code Online (Sandbox Code Playgroud)

请注意,as.matrix遵守此规则:

> as.matrix(x)
     [,1]
[1,]    1
[2,]    2
[3,]    3
Run Code Online (Sandbox Code Playgroud)

我认为您应该阅读?crossprod帮助页面以了解更多详细信息和背景。