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:
[,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