Matlab

How to Extract Diagonal Elements of a Matrix in MATLAB?

Matrices are the building blocks in MATLAB and are utilized in several applications of science and engineering. In MATLAB, we can perform many matrices operations. One of these operations is to extract diagonal entries of a matrix. In this article, we are going to learn how to extract diagonal entries of a matrix in MATLAB using some examples.

How to Extract the Diagonal Entries of a Matrix in MATLAB?

We can extract the diagonal elements of the specified matrix A using the diag() function. The diag() is a built-in function in MATLAB used for creating diagonal matrices or getting the diagonal elements of a matrix. This function accepts a matrix as an input and returns a column vector v containing diagonal entries of matrix A. The function follows a simple syntax that is given below:

v = diag(A)
v = diag(A,k)

Here:

The function v = diag(A) returns a column vector of A’s diagonal elements.

The function v = diag(A,k) provides the column vector containing the entries on A’s kth diagonal position.

Examples

Consider some examples to understand the functionality of the diag() function in MATLAB.

Example 1

In this example, we use the diag() function to extract the elements of the given matrix A and get a column vector v containing all diagonal entries of matrix A.

A = [1 2 3; 4 5 6; 7 8 0];
v = diag(A)

Example 2

Using the given MATLAB code, we extract the elements of the 1st diagonal of the given matrix A and get a column vector v containing all diagonal entries corresponding to the specified diagonal.

A = [1 2 3; 4 5 6; 7 8 0];
v = diag(A, 1)

Similarly, diag(A, 2) will give 3, and diag(A, -1) will give 4, 8 as output.

Conclusion

The diagonal entries of the given matrix A can be extracted using the diag() function. The diag() is a built-in function in MATLAB that allows us to create diagonal matrices or get the diagonal entries of a matrix. This function accepts a matrix as an argument and returns a column vector v containing diagonal entries of matrix A. This guide discovered how to extract diagonal elements of the given matrix using the diag() function in MATLAB.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.