Reputation:
Suppose I have a matrix. Suppose I have a list of a lower triangular matrix. How can I count the number of the elements in the matrices?
For example,
Matrix <- c(0, 4, 3, 1, 2,
0, 0, 3, 2, 1,
0, 0, 0, 2, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 0)
Matrix <- matrix(Matrix, 5, 5)
> Matrix
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 0 0
[2,] 4 0 0 0 0
[3,] 3 3 0 0 0
[4,] 1 2 2 0 0
[5,] 2 1 1 1 0
How to count the number of the elements in this matrix? This matrix contains 10 elements. How to count it in R?
Upvotes: 5
Views: 7250
Reputation: 389205
We can get the lower triangle elements using the function lower.tri
and then we can sum over them to count number of elements.
sum(lower.tri(Matrix))
#[1] 10
where
lower.tri(Matrix) #returns
# [,1] [,2] [,3] [,4] [,5]
#[1,] FALSE FALSE FALSE FALSE FALSE
#[2,] TRUE FALSE FALSE FALSE FALSE
#[3,] TRUE TRUE FALSE FALSE FALSE
#[4,] TRUE TRUE TRUE FALSE FALSE
#[5,] TRUE TRUE TRUE TRUE FALSE
Upvotes: 2
Reputation: 258
For a matrix of size n x n, the number of elements in the lower triangle is
n * (n - 1) / 2
Upvotes: 15