[R] Sum of Product in a Matrix

Marcio Resende mresendeufv at yahoo.com.br
Wed Sep 23 05:25:16 CEST 2009


Hi, 
I am new in R and I don´t know how to sum the product of two elements at the
time in a matrix

X=[ 1  5   9   13
      2  6  10  14
      3  7  11  15
      4  8  12  16]
I would like to do (1*5+2*6+3*7+4*8)
I need to do it step by step because I will further put a conditional in the
formula

It worked this way
x <- matrix ( c (1 : 16),ncol = 4)  #generating my x matrix
qw <- matrix (0, ncol = 4, nrow = 4) 
answer<- matrix (0, ncol = 4, nrow = 4) #my final objective is to generate
this matrix
soma <- function (d,q){  
(d [q, 1] * d [q, 2])   #a function to multiplicate two collumns and two
elements at a time
}
for (q in 1:4){
m <- soma
qw [q, 2] <- m (d, q)
}
answer <- sum (qw [, 2])

However I am doing this to generate a X'X matrix (since I can´t do t(X)$*$X
because i would like to include a conditional in the formula. Threrefore
this script above is not good to me)

Could anybody help me?
Thanks in advance
-- 
View this message in context: http://www.nabble.com/Sum-of-Product-in-a-Matrix-tp25530977p25530977.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list