【问题标题】:sum of multiplication of two columns of a matrix in RR中矩阵的两列相乘之和
【发布时间】:2013-02-17 02:14:13
【问题描述】:

我正在使用以下方法在 R 中生成一个矩阵,

ncolumns = 3
nrows = 10
my.mat <- matrix(runif(ncolumns*nrows), ncol=ncolumns)

这个矩阵表示一个点在 3D 中的坐标。如何在R中计算跟随?

sum of x(i)*y(i)

例如如果矩阵是,

x y z
1 2 3
4 5 6

然后输出 = 1*2 + 4*5

我正在努力学习 R。因此,我们将不胜感激。

谢谢

【问题讨论】:

  • 为了将来参考,这被称为“内积”或“点积”。

标签: r matrix dot-product


【解决方案1】:

您正在寻找 %*% 函数。

ncolumns = 3
nrows = 10

my.mat <- matrix(runif(ncolumns*nrows), ncol=ncolumns)

(my.answer <- my.mat[,1] %*% my.mat[,2])

#       [,1]
# [1,] 1.519

【讨论】:

  • 等价于sum(my.mat[,1]*my.mat[,2]),但作为一个矩阵。
  • 没错,这正是 mrn 想要的。
  • @MatthewLundberg 和 Nathan G 非常感谢您的宝贵时间。
【解决方案2】:

你只需这样做:

#  x is the first column; y is the 2nd
sum(my.mat[i, 1] * my.mat[i, 2])

现在,如果要命名列,可以直接引用它们

colnames(my.mat) <- c("x", "y", "z")

sum(my.mat[i, "x"] * my.mat[i, "y"])

# or if you want to get the product of each i'th element 
#  just leave empty the space where the i would go
sum(my.mat[ , "x"] * my.mat[ , "y"])

【讨论】:

  • 非常感谢您抽出宝贵的时间。您的回答也清除了我的其他几个疑问。
【解决方案3】:

每一列都由[]中的第二个参数指定,所以

my_matrix[,1] + my_matrix[,2] 

就是你所需要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2017-10-09
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多