[R] Odp: Sum of Product in a Matrix

Petr PIKAL petr.pikal at precheza.cz
Wed Sep 23 09:24:28 CEST 2009


Hi

I am not sure if I understand what you want but if your matrix is not so 
big you can try

> x[,1]*x[,2]
[1]  5 12 21 32
> cumsum(x[,1]*x[,2])
[1]  5 17 38 70
>

and than check value of cumsum according to your condition.

Regards
Petr



r-help-bounces at r-project.org napsal dne 23.09.2009 05:25:16:

> 
> 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.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list