Diagonal extraction
Read a matrix's main or offset diagonal for inspection or computation.
NumPy · Function
Extract a selected diagonal from a 2-D array or build a 2-D diagonal array from 1-D values. Use k to choose an offset from the main diagonal.
For a two-dimensional input, the function extracts the selected diagonal as a one-dimensional array. For a one-dimensional input, it creates a two-dimensional array containing those values on the selected diagonal and fills the remaining positions with zeros.
numpy.diag(v, k=0)| Name | Type | Description |
|---|---|---|
v | array_like | An array-like object. If it is two-dimensional, the selected diagonal is extracted; if it is one-dimensional, a two-dimensional diagonal array is constructed. |
k | int, optional | The diagonal offset. The default is 0; positive values select diagonals above the main diagonal and negative values select diagonals below it. |
out ndarray: the extracted diagonal or constructed diagonal array.
import numpy as np
matrix = np.arange(9).reshape(3, 3)
print(np.diag(matrix, k=1))
print(np.diag([10, 20, 30], k=-1))The first call extracts the diagonal above the main diagonal; the second constructs a matrix with the values below the main diagonal.
Read a matrix's main or offset diagonal for inspection or computation.
Create a square or offset-diagonal matrix from a vector of values.
Round-trip a matrix diagonal by extracting it and constructing a diagonal-only matrix.
With a two-dimensional input, np.diag returns the specified diagonal as a one-dimensional array. With a one-dimensional input, it places the values on the requested diagonal of a two-dimensional result.
Follow-up: How does k select the diagonal? Positive k selects diagonals above the main diagonal, while negative k selects those below it.
The k parameter identifies which diagonal is involved, and its default is 0, the main diagonal. A positive value moves above that diagonal; a negative value moves below it.
Follow-up: What happens when k is omitted? The main diagonal is selected or constructed because k defaults to 0.
The function returns an ndarray containing either the extracted diagonal or the constructed diagonal matrix. Its result shape therefore depends on whether v is two-dimensional or one-dimensional.
Follow-up: How can a diagonal matrix be made from an existing matrix's diagonal? Extract it first with np.diag, then pass that one-dimensional result back to np.diag.
numpy.diagonalnumpy.diagflat