我使用以下生成中的R矩陣的矩陣的兩列的乘法,總和中的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矩陣的矩陣的兩列的乘法,總和中的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.因此,任何幫助將是非常讚賞。
感謝
您正在尋找的%。*%功能。
ncolumns = 3
nrows = 10
my.mat <- matrix(runif(ncolumns*nrows), ncol=ncolumns)
(my.answer <- my.mat[,1] %*% my.mat[,2])
# [,1]
# [1,] 1.519
你根本:
# 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"])
非常感謝你的時間。您的回答也清除了我的其他幾項查詢。 – mrn 2013-02-17 02:30:34
爲了將來的參考,這被稱爲'內積'或'點積'。 – N8TRO 2013-02-17 02:34:16