Method:
np.diag(v, k=0)
Extracts a diagonal from a 2D array or constructs a diagonal matrix.
Returns:
np.ndarray
Parameters:
v: array-like-
A 1D array to place along the diagonal or a 2D matrix from which to extract the diagonal.
import numpy as np
result = np.diag(v=[1, 2, 3])
print(result)
'''
Output:
[[1 0 0]
[0 2 0]
[0 0 3]]
'''
k: int, Optional-
The diagonal offset (default 0). A positive value refers to an upper diagonal, and a negative value to a lower diagonal.
k = 0 (default) +
The diagonal offset is 0,0.
import numpy as np
result = np.diag(v=[1,2,3], k=0)
print(result)
'''
Output:
[[1 0 0]
[0 2 0]
[0 0 3]]
'''
k = 1 +
The diagonal offset is 0,1.
import numpy as np
result = np.diag(v=[1,2,3], k=1)
print(result)
'''
Output:
[[0 1 0 0]
[0 0 2 0]
[0 0 0 3]
[0 0 0 0]]
'''
k = -1 +
The diagonal offset is 1,0.
import numpy as np
result = np.diag(v=[1,2,3], k=-1)
print(result)
'''
Output:
[[0 0 0 0]
[1 0 0 0]
[0 2 0 0]
[0 0 3 0]]
'''