Given the number of rows in a symmetric matrix, calculate the row and column indices of the upper or lower triangles.

TriIndex(Nrow, which = "lower")

Arguments

Nrow

The number of rows

which

Specify which = "lower" or which = "upper". Defaults to "lower".

Value

A two-column matrix.

Note

A straightforward way to do this is to use which(lower.tri(YourMatrix), arr.ind = TRUE), however, this can be quite slow as the number of rows increases.

References

http://stackoverflow.com/a/20899060/1270695

Author

Ananda Mahto

Examples

TriIndex(4)
#> row col #> [1,] 2 1 #> [2,] 3 1 #> [3,] 4 1 #> [4,] 3 2 #> [5,] 4 2 #> [6,] 4 3
TriIndex(4, "upper")
#> row col #> [1,] 1 2 #> [2,] 1 3 #> [3,] 2 3 #> [4,] 1 4 #> [5,] 2 4 #> [6,] 3 4
m <- matrix(0, nrow = 4, ncol = 4) which(lower.tri(m), arr.ind = TRUE)
#> row col #> [1,] 2 1 #> [2,] 3 1 #> [3,] 4 1 #> [4,] 3 2 #> [5,] 4 2 #> [6,] 4 3