2013-02-17 37 views
3

我使用以下生成中的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.因此,任何幫助將是非常讚賞。

感謝

+1

爲了將來的參考,這被稱爲'內積'或'點積'。 – N8TRO 2013-02-17 02:34:16

回答

6

您正在尋找的%。*%功能。

ncolumns = 3 
nrows = 10 

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

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

#  [,1] 
# [1,] 1.519 
+1

等同於'sum(my.mat [,1] * my.mat [,2])',但是作爲矩陣。 – 2013-02-17 02:23:36

+0

的確,這正是我想要的。 – N8TRO 2013-02-17 02:26:17

+0

@MatthewLundberg和Nathan G非常感謝你的時間。 – mrn 2013-02-17 02:28:06

1

每列由第二個參數中指定[],所以

my_matrix[,1] + my_matrix[,2] 

是你所需要的。

+0

非常感謝你的時間。 – mrn 2013-02-17 02:28:36

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"]) 
+0

非常感謝你的時間。您的回答也清除了我的其他幾項查詢。 – mrn 2013-02-17 02:30:34