我使用下面的代码在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,所以任何帮助都将不胜感激。
谢谢
发布于 2013-02-17 10:21:30
您正在寻找%*%函数。
ncolumns = 3
nrows = 10
my.mat <- matrix(runif(ncolumns*nrows), ncol=ncolumns)
(my.answer <- my.mat[,1] %*% my.mat[,2])
# [,1]
# [1,] 1.519发布于 2013-02-17 10:20:21
您只需执行以下操作:
# 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"])发布于 2013-02-17 10:20:06
每一列都由[]中的第二个参数指定,因此
my_matrix[,1] + my_matrix[,2] 就是你所需要的。
https://stackoverflow.com/questions/14917323
复制相似问题