Creating Diagonal Matrices With A Vector Elements In MatLab®(Illustrated Expression)

There are lots of kinds of commands in Matlab® to make it easy to obtain various specific matrices shortly. So this feature of MatLab®, makes the MatLab® software is very desirable for matrix calculations. One of these useful matrix creation commands in Matlab® is the ‘diag()’ command. In this article, we will explain how to create diagonal matrices by using elements of a vector in Matlab.

How To Use ‘diag()’ Command In Matlab®?

>> a = [5 6 4 6 8];
b = diag(a)
c = diag([1 2 3])

b =

     5     0     0     0     0
     0     6     0     0     0
     0     0     4     0     0
     0     0     0     6     0
     0     0     0     0     8

c =

     1     0     0
     0     2     0
     0     0     3


We created a vector ‘a’ as shown above to create a diagonal matrix by using this vector. So we directly use the vector ‘a’ to create the diagonal matrix of ‘b’. If you look at the result of the ‘b’ as shown above, a diagonal matrix is created with elements of vector ‘a’ as diagonal elements. So you can directly use a vector variable inside the ‘diag()’ command in Matlab®.

Also, we created diagınal matrix ‘c’ as shown above. If you look at the result of ‘c’ as shown above, the diagonal matrix of ‘c’ is created with the elements of the vector that typed inside the ‘diag()’ command. So you can directly type the vector inside the ‘diag()’ command to obtain diagonal matrices in Matlab®.


So the use of the ‘diag()’ command in Matlab® is very simple like that to obtain diagonal matrices.

Do not forget to leave your comments and questions below about the ‘diag()’ command in Matlab® below. 

If you want further coding examples about the ‘diag()’ command in Matlab®, inform us in the comments.

This article is prepared for completely educative and informative purposes. Images used courtesy of Matlab®

Your precious feedbacks are very important to us.


Leave a Reply

Your email address will not be published. Required fields are marked *