R中的矩阵和向量乘法运算 [英] Matrix and vector multiplication operation in R

查看:1655
本文介绍了R中的矩阵和向量乘法运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I feel matrix operations in R is very confusing: we are mixing row and column vectors.

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

  • Here we define x1 as a vector, (I assume R default vector is a column vector? but it does not show it is arranged in that way.)

然后我们定义x2x1的转置,这对我来说也很奇怪.

Then we define x2 is a transpose of x1, which the display also seems strange for me.

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

Finally, if we define x3 as a matrix the display seems better.

现在,我的问题是,x1x2是完全不同的东西(一个是另一个的转置),但是我们在这里得到的结果是相同的.

Now, my question is that, x1 and x2 are completely different things (one is transpose of another), but we have the same results here.

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

Any explanations? may be I should not mix vector and matrix operations together?

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

推荐答案

请参见?`%*%`:

说明:

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

这篇关于R中的矩阵和向量乘法运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆