sum of multiplication of two columns of a matrix in R

mrn picture mrn · Feb 17, 2013 · Viewed 12.9k times · Source

I am generating a matrix in R using following,

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

This matrix indicates the co-ordinates of a point in 3D. How to calculate following in R?

sum of x(i)*y(i)

e.g. if the matrix is,

x y z
1 2 3
4 5 6

then output = 1*2 + 4*5

I'm trying to learn R. So any help will be really appreciated.

Thanks

Answer

N8TRO picture N8TRO · Feb 17, 2013

You're looking for the %*% function.

ncolumns = 3
nrows = 10

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

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

#       [,1]
# [1,] 1.519