title: R: subtraction of elements of a matrix from the elements of another matrix
body: <p>I am trying to apply an equation to two matrices. Since I am a beginner R user, it seems very difficult to me. I would be greatful if you could give me some advice.</p>
  
  <p>I have two similarity matrices:</p>
  
  <pre><code>&gt; r
       [,1] [,2] [,3] [,4] [,5] [,6]
  [1,]    0    4    2    2    5    5
  [2,]    4    0    8    3    3    2
  [3,]    2    8    0    4    4    3
  [4,]    2    3    4    0    0    3
  [5,]    5    3    4    0    0    5
  [6,]    5    2    3    3    5    0
  
  &gt; nr
       [,1] [,2] [,3] [,4] [,5] [,6]
  [1,]    0    4    7    2    4    3
  [2,]    4    0    5    2    3    2
  [3,]    7    5    0    3    2    2
  [4,]    2    2    3    0    7    2
  [5,]    4    3    2    7    0    5
  [6,]    3    2    2    2    5    0
  </code></pre>
  
  <p>And I wolud like to apply to these the following:</p>
  
  <pre><code>sum((r[i,j]-nr[i,j])^2)/6
  </code></pre>
  
  <p>My great problem is to extract elements of <code>nr</code> from the elements <code>r</code>.
  If I substitute <code>nr[i,j]</code> with a number, for example <code>0.4</code> then the following works perfectly:</p>
  
  <pre><code>s&lt;-numeric()
  for (i in 1:nrow(r))
  {
    for (j in 1:ncol(r))
  {
      s[k]&lt;-sum((r[i,j]-0.4)^2)/6
  }
  }
  &gt; s
  [1] 0.02666667
  </code></pre>
  
  <p>But I can't figure out how could I modify this code to solve the original problem. 
  I would appreciate any kind of help/suggestion. 
  Thanks!</p>