Question

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

Was it helpful?

Solution

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

OTHER TIPS

you simply do:

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

Now, if you want to name your columns, you can refer to them directly

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

each column is designated by the second argument in [], so

my_matrix[,1] + my_matrix[,2] 

is all you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top