Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- v : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, corresponds to the
(v, k=0)
| 305 | |
| 306 | @array_function_dispatch(_diag_dispatcher) |
| 307 | def diagflat(v, k=0): |
| 308 | """ |
| 309 | Create a two-dimensional array with the flattened input as a diagonal. |
| 310 | |
| 311 | Parameters |
| 312 | ---------- |
| 313 | v : array_like |
| 314 | Input data, which is flattened and set as the `k`-th |
| 315 | diagonal of the output. |
| 316 | k : int, optional |
| 317 | Diagonal to set; 0, the default, corresponds to the "main" diagonal, |
| 318 | a positive (negative) `k` giving the number of the diagonal above |
| 319 | (below) the main. |
| 320 | |
| 321 | Returns |
| 322 | ------- |
| 323 | out : ndarray |
| 324 | The 2-D output array. |
| 325 | |
| 326 | See Also |
| 327 | -------- |
| 328 | diag : MATLAB work-alike for 1-D and 2-D arrays. |
| 329 | diagonal : Return specified diagonals. |
| 330 | trace : Sum along diagonals. |
| 331 | |
| 332 | Examples |
| 333 | -------- |
| 334 | >>> np.diagflat([[1,2], [3,4]]) |
| 335 | array([[1, 0, 0, 0], |
| 336 | [0, 2, 0, 0], |
| 337 | [0, 0, 3, 0], |
| 338 | [0, 0, 0, 4]]) |
| 339 | |
| 340 | >>> np.diagflat([1,2], 1) |
| 341 | array([[0, 1, 0], |
| 342 | [0, 0, 2], |
| 343 | [0, 0, 0]]) |
| 344 | |
| 345 | """ |
| 346 | try: |
| 347 | wrap = v.__array_wrap__ |
| 348 | except AttributeError: |
| 349 | wrap = None |
| 350 | v = asarray(v).ravel() |
| 351 | s = len(v) |
| 352 | n = s + abs(k) |
| 353 | res = zeros((n, n), v.dtype) |
| 354 | if (k >= 0): |
| 355 | i = arange(0, n-k, dtype=intp) |
| 356 | fi = i+k+i*n |
| 357 | else: |
| 358 | i = arange(0, n+k, dtype=intp) |
| 359 | fi = i+(i-k)*n |
| 360 | res.flat[fi] = v |
| 361 | if not wrap: |
| 362 | return res |
| 363 | return wrap(res) |
| 364 |