VOOZH about

URL: https://www.geeksforgeeks.org/r-language/convert-a-vector-into-a-diagonal-matrix-in-r/

⇱ Convert a vector into a diagonal matrix in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert a vector into a diagonal matrix in R

Last Updated : 23 Jul, 2025

In this article, we will examine various methods to convert a vector into a diagonal matrix by using R Programming Language.

What is a diagonal matrix?

A diagonal matrix is a special type of square matrix where all elements, except those on the main diagonal (running from the top-left to the bottom-right), are zeros. This diagonal matrix can contain data of many types such as strings, integers, characters, and logic. It is possible to access the diagonal elements by using the built-in functions provided by R.

Converting a vector into a diagonal matrix

R language offers various methods to efficiently convert a vector into a diagonal matrix. By using these methods provided by R, it is easy to convert a vector into a diagonal matrix. Some of the methods to convert a vector into a diagonal matrix are

Converting a vector into a diagonal matrix by using the diag() function

This method is used to convert a vector into a diagonal matrix more efficiently.

Syntax

diag(y, nrow = NULL, ncol = NULL, diag = FALSE)

In the below example, we converted a vector into 5*5 diagonal matrix.

Output:

[1] "The vector is"
[1] 7 6 4 3 2

[1] "The diagonal matrix "
[,1] [,2] [,3] [,4] [,5]
[1,] 7 0 0 0 0
[2,] 0 6 0 0 0
[3,] 0 0 4 0 0
[4,] 0 0 0 3 0
[5,] 0 0 0 0 2

In the below example, we converted a vector into 6*6 diagonal matrix.

Output:

[1] 20 25 30 35 40 45

[1] "The diagonal matrix is"
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 20 0 0 0 0 0
[2,] 0 25 0 0 0 0
[3,] 0 0 30 0 0 0
[4,] 0 0 0 35 0 0
[5,] 0 0 0 0 40 0
[6,] 0 0 0 0 0 45

Converting a vector into a diagonal matrix by using matrix multiplication

These method is used to convert a vector into a digonal matrix by using functions provided by R.

Syntax

res = matrix1%*%matrix2

In the below example, we converted a vector into the 4*4 diagonal matrix.

Output:

[1] "The vector is"
[1] 9 8 6 5

[1] "The diagonal matrix is"
[,1] [,2] [,3] [,4]
[1,] 9 0 0 0
[2,] 0 8 0 0
[3,] 0 0 6 0
[4,] 0 0 0 5

In the below example, we converted a vector into 6*6 diagonal matrix

Output:

[1] "The vector is"
[1] 20 25 30 35 40 45

[1] "The diagonal matrix is"
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 20 0 0 0 0 0
[2,] 0 25 0 0 0 0
[3,] 0 0 30 0 0 0
[4,] 0 0 0 35 0 0
[5,] 0 0 0 0 40 0
[6,] 0 0 0 0 0 45

Conclusion

In conclusion, we learned various methods to convert the vector into a diagonal matrix. R language offers versatile tools, while converting the vector into a diagonal matrix.

Comment
Article Tags:
Article Tags:

Explore