title: R loop for calculating matrix elements taking too long to execute
body: <p>The following loop is taking a lot of time to run. If I comment the line inside, it runs quickly. <code>prices</code> is <code>3224x40</code> matrix.</p>
  
  <pre><code>get_returns &lt;- function(prices, type=1) {  
    returns = prices
    returns2 = prices
    returns[,] = 0
    M = dim(prices)[1]
    N = dim(prices)[2]
  
    for (i in 2:M) {
      for (j in 1:N) {      
        returns[i,j] = prices[i,j]/prices[i-1,j] - 1   ## LINE 1
        returns2[i,j] = prices[i,j]/prices[1,j] - 1   ## LINE 1
      }
    }
  }
  
  &gt; dim(prices)
  [1] 3224   40
  
  &gt;
  &gt; system.time(get_returns(prices,1))
     user  system elapsed 
  1213.95    1.12 1266.60 
  &gt; 
  
  &gt; # After commenting LINE 1
  &gt; system.time(get_returns(prices,1))
     user  system elapsed 
     0.67    0.00    0.75 
  &gt;
  </code></pre>
  
  <p>It is almost taking 20 minutes to run. I am wondering why would it take this long to run and if I can do something to optimize it. I have other loops which run fairly fast but this particular loop is a problem.</p>