Skip to content
Prev 131684 / 398502 Next

for (i in...)

At 3:27 PM -0500 12/9/07, Duncan Murdoch wrote:
Rina,
   Alternatively, you could avoid the entire double loop by using 
matrix operations.  I show this and then reproduce it using the first 
section of your code:

#how to use matrices to avoid looping
n_trait <- 5
X <- matrix( rnorm(100*n_trait),ncol= n_trait) #create a data matrix
G_o <- t(X) %*% X   #create the G_o matrix as a  matrix of cross products
G_o          #show the cross products

dG <- diag(1/sqrt(diag(G_o)))  #divide by the sqrt of the diagonal
rG <- dG %*% G_o %*% dG
rG                              #show the result
#######################
  #abbreviated Rina code using loops
  for(i in 1:n_trait){
     for( j in 1:n_trait){
  rG[i,j] <- G_o[i,j]/(sqrt(G_o[i,i]%*%G_o[j,j])) }}
rG         #compare to above



Bill