# How to find the row and column index for upper triangular matrix elements in R?

To find the row and column index for upper triangular matrix elements in R, we can follow the below steps −

• First of all, create a matrix.
• Then, use which function with upper.tri function to find the row and column index for upper triangular matrix elements.
• After, that attach the values corresponding to each index using cbind function.

## Create the matrix

Let’s create a matrix as shown below −

Live Demo

M<-matrix(1:25,nrow=5)
M

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    [,1] [,2] [,3] [,4] [,5]
[1,] 1    6   11    16    21
[2,] 2    7   12    17    22
[3,] 3    8   13    18    23
[4,] 4    9   14    19    24
[5,] 5   10   15    20    25

## Find the row and column index

Using which function with upper.tri function to find the row and column for upper triangular matrix in M −

Live Demo

M<-matrix(1:25,nrow=5)
Index<-which(upper.tri(M,diag=TRUE),arr.ind=TRUE)
Index

## Output

   row col
[1,] 1 1
[2,] 1 2
[3,] 2 2
[4,] 1 3
[5,] 2 3
[6,] 3 3
[7,] 1 4
[8,] 2 4
[9,] 3 4
[10,] 4 4
[11,] 1 5
[12,] 2 5
[13,] 3 5
[14,] 4 5
[15,] 5 5

## Attach the values from matrix

Using cbind function to attach the matrix values to indices for row and column −

Live Demo

M<-matrix(1:25,nrow=5)
Index<-which(upper.tri(M,diag=TRUE),arr.ind=TRUE)
cbind(Index,M[Index])

## Output

  row col
[1,] 1 1 1
[2,] 1 2 6
[3,] 2 2 7
[4,] 1 3 11
[5,] 2 3 12
[6,] 3 3 13
[7,] 1 4 16
[8,] 2 4 17
[9,] 3 4 18
[10,] 4 4 19
[11,] 1 5 21
[12,] 2 5 22
[13,] 3 5 23
[14,] 4 5 24
[15,] 5 5 25

Updated on: 13-Aug-2021

274 Views