title: compute only diagonals of matrix multiplication in R
body: <p>I need only the diagonal elements from a matrix multiplication:</p>
  
  <p><img src="https://i.stack.imgur.com/4XV2u.gif" alt="enter image description here">,</p>
  
  <p>in R. As Z is huge I want to avoid the full out multiplication....</p>
  
  <pre><code>Z &lt;- matrix(c(1,1,1,2,3,4), ncol = 2)
  Z
  #     [,1] [,2]
  #[1,]    1    2
  #[2,]    1    3
  #[3,]    1    4
  
  X &lt;- matrix(c(10,-5,-5,20), ncol = 2)
  X
  #     [,1] [,2]
  #[1,]   10   -5
  #[2,]   -5   20
  
  Z %*% D %*% t(Z)
  #     [,1] [,2] [,3]
  #[1,]   70  105  140
  #[2,]  105  160  215
  #[3,]  140  215  290
  
  diag(Z %*% D %*% t(Z))
  #[1]  70 160 290
  </code></pre>
  
  <p>X is always a small square matrix (2x2 , 3x3 or 4x4), where Z will have the number of columns equal to the dimension of X. Is there a function available to do this?</p>