What is a diagonal matrix?
A diagonal matrix is a square matrix in which all elements other than the elements in the principal diagonal are zero. So, if A is a square matrix and Ai,j is the element in the ith row and jth column, then
Let’s look at an example. The matrix A given below is an example of a diagonal matrix.
How to create a diagonal matrix using Python NumPy?
We can use the following Python code to create a diagonal matrix using NumPy.
import numpy diagonal = [1, 2, 3] A = numpy.diag(diagonal) print("The diagonal matrix A: \n", A)
Here, we are creating a diagonal matrix the principal diagonal of which contains the elements [1, 2, 3]. We are using the function numpy.diag() for creating the diagonal matrix with the given principal diagonal.
The output of the mentioned program will be:
The diagonal matrix A: [[1 0 0] [0 2 0] [0 0 3]]






0 Comments