Fill matrix diagonal with different values for each python numpy

后端 未结 2 1684
南旧
南旧 2021-01-12 19:48

I saw a function numpy.fill_diagonal which assigns same value for diagonal elements. But I want to assign different random values for each diagonal elements. Ho

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 20:40

    That the docs call the fill val a scalar is an existing documentation bug. In fact, any value that can be broadcasted here is OK.

    Fill diagonal works fine with array-likes:

    >>> a = np.arange(1,10).reshape(3,3)
    >>> a
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    >>> np.fill_diagonal(a, [99, 42, 69])
    >>> a
    array([[99,  2,  3],
           [ 4, 42,  6],
           [ 7,  8, 69]])
    

    It's a stride trick, since the diagonal elements are regularly spaced by the array's width + 1.

    From the docstring, that's a better implementation than using np.diag_indices too:

    Notes
    -----
    .. versionadded:: 1.4.0
    
    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.
    

提交回复
热议问题