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

Matrix and vector multiplication operation in R

我觉得 R 中的矩阵运算非常混乱:我们混合了行向量和列向量。

现在,我的问题是,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

参见?`%*%`

Description:

 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).

尝试以下方法

library(optimbase)
x1 = c(1:3)
x2 = transpose(x1)

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

相对于:

x2.t = t(x1)
x2.t
     [,1] [,2] [,3]
[1,]    1    2    3

参见 transpose

的文档

transpose is a wrapper function around the t function, which tranposes matrices. Contrary to t, transpose processes vectors as if they were row matrices.

长度为 3 的数值向量不是 "column vector",因为它没有维度。但是,它确实被 %*% 处理,就好像它是一个维度为 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

而这不是:

 A %*% x
#Error in A %*% x : non-conformable arguments

在与 n x 1 维矩阵相同的基础上处理原子向量是有意义的,因为 R 使用列优先索引处理其矩阵操作。而R的结合律规则是从左到右进行的,所以这也成功了:

  y <- 1:4
 x %*% A %*% y
#--------------    
 [,1]
[1,]  500

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

> as.matrix(x)
     [,1]
[1,]    1
[2,]    2
[3,]    3

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