Search code examples
rnestedmatrix-multiplication

Converting nested summation to R type matrix multiplication


I am trying to implement a nested summation in R. The for loop implementation is:

 sum = 0
  for(i in 1:n){
    for(j in 1:n){
      for(k in 1:n){
        sum = sum + w[i,j]*w[j,k]
      }
    }
  }

where w is a symmetric square matrix and n is the number of rows (or columns). Please see the formula I am trying to implement. (SO did not allow me to write Latex nor add the image here.)

The nested for loops above takes forever. How do I implement this efficiently the R way?


Solution

  • Try this:

    Sum2 <- sum(w %*% w)
    
    all.equal(Sum, Sum2)
    ## [1] TRUE
    

    Note

    We used for comparison:

    # input
    set.seed(123)
    n <- 5
    w <- matrix(rnorm(n^2), n)
    
    # from question
    Sum = 0
      for(i in 1:n){
        for(j in 1:n){
          for(k in 1:n){
            Sum = Sum + w[i,j]*w[j,k]
          }
        }
      }