[R] Help with improving efficiency

Wolfgang Viechtbauer wviechtb at s.psych.uiuc.edu
Fri Aug 9 22:40:14 CEST 2002


Dear All,

I have a problem that I think could be solved much more efficiently, but
I don't have a clue how to accomplish this. I have a matrix W with
dimensions k*(p+1):

Let's say W is 5*4 and looks like this:

> W
      [,1] [,2] [,3] [,4]
 [1,]    1   -1   -1    1
 [2,]    1    1    1    1
 [3,]    1    2   -2   -1
 [4,]    1    0   -1   -1
 [5,]    1   -2   -1    0

I want to take each row (a p*1 vector), transpose it (1*p column
vector), and then multiply that by the same row vector, which will give
me a p*p matrix. So, for each row, I calculate:

as.matrix(W[i,]) %*% W[i,]	for i = 1, ..., k.

Next, I want to find the sum of the k (p*p) matrices. The following code
seems to work fine:


k <- 5
p <- 3
W <- matrix(c( rep(1, k), round(rnorm(n=(p*k), mean=0, sd=1), 0)),
     ncol=(p+1), nrow=k) 		# create a random W matrix
m1 <- matrix(0, nrow=p+1, ncol=p+1)
for (i in 1:k) {
   m1 <- m1 + as.matrix(W[i,]) %*% W[i,]
}


but this just seems terribly inefficient. Any suggestions for improving
this? Thanks in advance.

Wolfgang


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list