bundles / numpy 2.4.3 / numpy / fill_diagonal
_ArrayFunctionDispatcher
numpy:fill_diagonal
Signature
def fill_diagonal ( a , val , wrap = False ) Summary
Fill the main diagonal of the given array of any dimensionality.
Extended Summary
For an array a with a.ndim >= 2, the diagonal is the list of values a[i, ..., i] with indices i all identical. This function modifies the input array in-place without returning a value.
Parameters
a: array, at least 2-D.Array whose diagonal is to be filled in-place.
val: scalar or array_likeValue(s) to write on the diagonal. If
valis scalar, the value is written along the diagonal. If array-like, the flattenedvalis written along the diagonal, repeating if necessary to fill all diagonal entries.wrap: boolFor tall matrices in NumPy version up to 1.6.2, the diagonal "wrapped" after N columns. You can have this behavior with this option. This affects only tall matrices.
Notes
This functionality can be obtained via diag_indices, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing.
Examples
import numpy as np a = np.zeros((3, 3), int) np.fill_diagonal(a, 5) a✓
a = np.zeros((3, 3, 3, 3), int) np.fill_diagonal(a, 4)✓
a[0, 0] a[1, 1] a[2, 2]✓
a = np.zeros((5, 3), int) np.fill_diagonal(a, 4) a✓
a = np.zeros((5, 3), int) np.fill_diagonal(a, 4, wrap=True) a✓
a = np.zeros((3, 5), int) np.fill_diagonal(a, 4, wrap=True) a✓
a = np.zeros((3, 3), int); np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip a np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip a✓
See also
- diag_indices
- diag_indices_from
Aliases
-
numpy.fill_diagonal