hxd*_*011 1 r vector matrix matrix-multiplication
我觉得R中的矩阵运算非常令人困惑:我们正在混合行向量和列向量。
在这里,我们定义x1
为向量(我假设R默认向量是列向量吗?但它没有显示它是以这种方式排列的。)
然后我们定义x2
的转置x1
,这对我来说也很奇怪。
最后,如果我们定义x3
为矩阵,则显示效果会更好。
现在,我的问题是,x1
和x2
是完全不同的东西(一个是另一个转),但我们这里有同样的结果。
有什么解释吗?可能我不应该将向量和矩阵运算混合在一起吗?
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)
见?`%*%`
:
描述:
Run Code Online (Sandbox Code Playgroud)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).
长度为 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
帮助页面以了解更多详细信息和背景。