# How to convert a vector into a diagonal matrix in R?

R ProgrammingServer Side ProgrammingProgramming

A diagonal matrix is a type of square matrix that contains zero at non-diagonal elements starting from left-upper to right-bottom. To convert a vector into a diagonal matrix in R, we can use diag function along with matrix function and use ncol argument where we can put the number of columns equal to the number of values in the vector. Check out the Examples given below to understand how it can be done.

## Example 1

Following snippet a sample list −

V1<-rpois(5,10)
V1

The following vector is created −

 9 8 4 8 9

Following snippet creates a sample matrix −

V1<-rpois(5,10)
M1<-matrix(diag(V1),ncol=5)
M1

The following matrix is created −

   [,1] [,2] [,3] [,4] [,5]
[1,] 9    0   0     0    0
[2,] 0    8   0     0    0
[3,] 0    0   4     0    0
[4,] 0    0   0     8    0
[5,] 0    0   0     0    9

## Example 2

Following snippet a sample list −

V2<-rpois(5,500)
V2

The following vector is created −

 500 484 487 515 460

Following snippet creates a sample matrix −

V2<-rpois(5,500)
M2<-matrix(diag(V2),ncol=5)
M2

The following matrix is created −

    [,1] [,2] [,3] [,4] [,5]
[1,] 500   0    0    0    0
[2,] 0   484    0    0    0
[3,] 0     0  487    0    0
[4,] 0     0    0  515    0
[5,] 0     0    0    0  460

## Example 3

Following snippet a sample list −

V3<-sample(1:100,5)
V3

The following vector is created −

 19 72 11 95 5

Following snippet creates a sample matrix −

V3<-sample(1:100,5)
M3<-matrix(diag(V3),ncol=5)
M3

The following matrix is created −

   [,1] [,2] [,3] [,4] [,5]
[1,] 19   0    0    0    0
[2,] 0   72    0    0    0
[3,] 0    0   11    0    0
[4,] 0    0    0   95    0
[5,] 0    0    0    0    5

## Example 4

Following snippet a sample list −

V4<-round(rnorm(5),2)
V4

The following vector is created −

 -0.81 -1.12 -0.98 -1.59 0.58

Following snippet creates a sample matrix −

V4<-round(rnorm(5),2)
M4<-matrix(diag(V4),ncol=5)
M4

The following matrix is created −

     [,1]   [,2]  [,3]  [,4] [,5]
[1,] -0.81  0.00  0.00 0.00  0.00
[2,]  0.00 -1.12  0.00 0.00  0.00
[3,]  0.00  0.00 -0.98 0.00  0.00
[4,]  0.00  0.00  0.00 -1.59 0.00
[5,]  0.00  0.00  0.00 0.00  0.58

## Example 5

Following snippet a sample list −

V5<-round(rnorm(5,10,0.5),2)
V5

The following vector is created −

 10.43 8.89 9.79 10.50 9.29

Following snippet creates a sample matrix −

V5<-round(rnorm(5,10,0.5),2)
M5<-matrix(diag(V5),ncol=5)
M5

The following matrix is created −

      [,1] [,2] [,3]  [,4] [,5]
[1,] 10.43 0.00 0.00  0.0 0.00
[2,] 0.00  8.89 0.00  0.0 0.00
[3,] 0.00  0.00 9.79  0.0 0.00
[4,] 0.00  0.00 0.00 10.5 0.00
[5,] 0.00  0.00 0.00  0.0 9.29