flopscope.numpy.diag
fnp.diag(v, k=0)[flopscope source][numpy source]
Extract a diagonal or construct a diagonal array.
Adapted from NumPy docs np.diag
Cost
4×per-operation
Flopscope Context
Extract diagonal or construct diagonal array. Cost: len(diagonal).
See the more detailed documentation for flops.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using.
Parameters
- v:array_like
If
vis a 2-D array, return a copy of itsk-th diagonal. Ifvis a 1-D array, return a 2-D array withvon thek-th diagonal.- k:int, optional
Diagonal in question. The default is 0. Use
k>0for diagonals above the main diagonal, andk<0for diagonals below the main diagonal.
Returns
- out:ndarray
The extracted diagonal or constructed diagonal array.
See also
- we.flops.diagonal Return specified diagonals.
- we.flops.diagflat Create a 2-D array with the flattened input as a diagonal.
- we.flops.trace Sum along diagonals.
- we.flops.triu Upper triangle of an array.
- we.flops.tril Lower triangle of an array.
Examples
>>> import flopscope.numpy as fnp
>>> x = flops.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])>>> flops.diag(x)
array([0, 4, 8])
>>> flops.diag(x, k=1)
array([1, 5])
>>> flops.diag(x, k=-1)
array([3, 7])>>> flops.diag(flops.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])