title: Sum all the elements in a matrix using a loop
body: <p>In R, I have a 5x5 matrix called <code>P</code> like this:</p>
  
  <pre><code>1  3  0  0  0
  0  3  0  0  0
  0  3  1  0  0
  0  3  0  1  0
  0  3  0  0  1
  </code></pre>
  
  <p>and want to sum all its elements. I know I can do <code>sum(P)</code> and get 19. But I want to do this using a for or while loop.</p>
  
  <p>One idea was to do</p>
  
  <pre><code>result &lt;- 0
  for(i in col(P)) { result &lt;- result + sum(i)}
  </code></pre>
  
  <p>however this gives me that the sum (<code>result</code>) is 75 and even after printing the result variable, I can't understand why.</p>