0

I a have symmetric matrix (e.g. M <- matrix(1:4, ncol = 2)) and I want to set the off diagonal elements to 0. Is there a smarter way than diag(diag(M), ncol = ncol(M))?

Note: diag does not support the usssage of diag(M, ncol = ncol(M)) and doesn't have an option like diag(M, as.matrix = TRUE) etc.

Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • `upper.tri(M) <- 0; lower.tri(M) <- 0` Is the first thing I could think of. – Ronak Shah Dec 10 '16 at 10:32
  • Your title is a little bit misleading. I would suggest put zeros off the diagonal of a matrix. – DJJ Dec 10 '16 at 11:38
  • 1
    I don't think it's misleading. Diagonal matrix is a matrix where off-diagonal elements are zero. –  Dec 10 '16 at 11:43
  • 1
    What do you mean by smarter? The approach you have in your post seems efficient in time, and @RonakShah's comment would be efficient in space if `M` is large. – aichao Dec 10 '16 at 13:26

0 Answers0