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,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.
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.
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.