Identifying if only the diagonal is non-zero
Clash Royale CLAN TAG#URR8PPP
Identifying if only the diagonal is non-zero
Let's say I have a matrix with all 0's with the exception of the diagonal.
m <- matrix(ncol=3,nrow=3)
m[,1] <- c(1,0,0)
m[,2] <- c(0,1,0)
m[,3] <- c(0,0,1)
What logical check could I use to test if the upper and lower triangle of the matrix are zero?
3 Answers
3
all(m[lower.tri(m)] == 0, m[upper.tri(m)] == 0)
or
all(m[!diag(nrow(m))] == 0)
– tim riffe
Jun 15 '12 at 21:22
all(m[!diag(nrow(m))] == 0)
Here's a slightly shorter alternative to @GregaKešpret's excellent solution:
m <- diag(11:13)
m
all(m[!diag(nrow(m))] == 0) # TRUE
m[1,2] = 0.01
all(m[!diag(nrow(m))] == 0) # FALSE
The diag
function has two major modes: Give it a vector as in diag(11:13)
and it puts it on the diagonal. Or give it a number as in diag(3)
and it creates a identity matrix of that size. Then I extract all the non-diagonal elements and compare them to 0.
diag
diag(11:13)
diag(3)
Simply check for:
sum(m) == sum(diag(m))
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
?all. Perfecto!
– Brandon Bertelsen
Jun 15 '12 at 20:21