VOOZH about

URL: https://www.geeksforgeeks.org/r-language/construct-a-diagonal-matrix-in-r-programming-diag-function/

⇱ Construct a Diagonal Matrix in R Programming - diag() Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct a Diagonal Matrix in R Programming - diag() Function

Last Updated : 15 Jul, 2025

diag() function in R Language is used to construct a diagonal matrix.
 

Syntax: diag(x, nrow, ncol)
Parameters: 
x: value present as the diagonal elements. 
nrow, ncol: number of rows and columns in which elements are represented. 
 


Example 1: 
 

Output: 
 

 [, 1] [, 2] [, 3]
[1, ] 1 0 0
[2, ] 0 1 0
[3, ] 0 0 1

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


Example 2: 
 

Output: 
 

 [, 1] [, 2] [, 3]
[1, ] 5 0 0
[2, ] 0 5 0

 [, 1] [, 2] [, 3]
[1, ] 10 0 0
[2, ] 0 10 0
[3, ] 0 0 10


 

Comment
Article Tags:

Explore