Loading [MathJax]/jax/output/HTML-CSS/config.js
lettura simple

Diagonal Matrices in Matlab

In this lesson, I will explain how to create diagonal matrices in Matlab.

What is a diagonal matrix? A diagonal matrix is a square matrix with non-zero elements on the main diagonal and zeros elsewhere. Here's an example of a diagonal matrix: $$ M = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \\ 0 & 0 & 3 & 0 \\ 0 & 0 & 0 & 4 \end{pmatrix} $$

To create a diagonal matrix in Matlab, you can use the diag() function.

diag(v)

The parameter 'v' is a vector containing the elements to be placed on the main diagonal of the matrix.

Let me show you a practical example.

Create a vector 'v' with four elements.

>> v=[1 2 3 4]
v =
1 2 3 4

Now type the command diag(v)

Matlab will create a 4x4 diagonal matrix with the elements from the vector 'v' on the main diagonal.

>> diag(v)
ans =
Diagonal Matrix
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4

All other elements of the matrix are zero.

$$ M = \begin{pmatrix} \color{red}1 & 0 & 0 & 0 \\ 0 & \color{red}2 & 0 & 0 \\ 0 & 0 & \color{red}3 & 0 \\ 0 & 0 & 0 & \color{red}4 \end{pmatrix} $$

You can achieve the same result by typing diag([1 2 3 4]) without assigning the vector to a variable.

In this case, remember to enclose the elements of the array in square brackets.

>> diag([1 2 3 4])
ans =
Diagonal Matrix

1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4

This way, you can create diagonal matrices of any size.

For example, to create a 3x3 diagonal matrix with three rows and three columns, type diag([3 4 1])

>> diag([3 4 1])
ans =
Diagonal Matrix
3 0 0
0 4 0
0 0 1

In this case, Matlab creates a 3x3 matrix because the vector has only three elements.

$$ M = \begin{pmatrix} \color{red}3 & 0 & 0 \\ 0 & \color{red}4 & 0 \\ 0 & 0 & \color{red}1 \end{pmatrix} $$




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin