Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.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 usi
(v, k=0)
| 259 | |
| 260 | @array_function_dispatch(_diag_dispatcher) |
| 261 | def diag(v, k=0): |
| 262 | """ |
| 263 | Extract a diagonal or construct a diagonal array. |
| 264 | |
| 265 | See the more detailed documentation for ``numpy.diagonal`` if you use this |
| 266 | function to extract a diagonal and wish to write to the resulting array; |
| 267 | whether it returns a copy or a view depends on what version of numpy you |
| 268 | are using. |
| 269 | |
| 270 | Parameters |
| 271 | ---------- |
| 272 | v : array_like |
| 273 | If `v` is a 2-D array, return a copy of its `k`-th diagonal. |
| 274 | If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th |
| 275 | diagonal. |
| 276 | k : int, optional |
| 277 | Diagonal in question. The default is 0. Use `k>0` for diagonals |
| 278 | above the main diagonal, and `k<0` for diagonals below the main |
| 279 | diagonal. |
| 280 | |
| 281 | Returns |
| 282 | ------- |
| 283 | out : ndarray |
| 284 | The extracted diagonal or constructed diagonal array. |
| 285 | |
| 286 | See Also |
| 287 | -------- |
| 288 | diagonal : Return specified diagonals. |
| 289 | diagflat : Create a 2-D array with the flattened input as a diagonal. |
| 290 | trace : Sum along diagonals. |
| 291 | triu : Upper triangle of an array. |
| 292 | tril : Lower triangle of an array. |
| 293 | |
| 294 | Examples |
| 295 | -------- |
| 296 | >>> import numpy as np |
| 297 | >>> x = np.arange(9).reshape((3,3)) |
| 298 | >>> x |
| 299 | array([[0, 1, 2], |
| 300 | [3, 4, 5], |
| 301 | [6, 7, 8]]) |
| 302 | |
| 303 | >>> np.diag(x) |
| 304 | array([0, 4, 8]) |
| 305 | >>> np.diag(x, k=1) |
| 306 | array([1, 5]) |
| 307 | >>> np.diag(x, k=-1) |
| 308 | array([3, 7]) |
| 309 | |
| 310 | >>> np.diag(np.diag(x)) |
| 311 | array([[0, 0, 0], |
| 312 | [0, 4, 0], |
| 313 | [0, 0, 8]]) |
| 314 | |
| 315 | """ |
| 316 | v = asanyarray(v) |
| 317 | s = v.shape |
| 318 | if len(s) == 1: |
searching dependent graphs…