为每个python numpy用不同的值填充矩阵对角线 [英] Fill matrix diagonal with different values for each python numpy
问题描述
我看到了一个函数numpy.fill_diagonal
,该函数为对角线元素分配相同的值.但是我想为每个对角线元素分配不同的随机值.我该如何在python中做到这一点?可能正在使用scipy或其他库?
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. How can I do it in python ? May be using scipy or other libraries ?
推荐答案
您可以使用 np.diag_indices
来获取那些索引,然后使用这些索引简单地索引到数组中并分配值.
You can use np.diag_indices
to get those indices and then simply index into the array with those and assign values.
这里是一个示例运行来说明它-
Here's a sample run to illustrate it -
In [86]: arr # Input array
Out[86]:
array([[13, 69, 35, 98, 16],
[93, 42, 72, 51, 65],
[51, 33, 96, 43, 53],
[15, 26, 16, 17, 52],
[31, 54, 29, 95, 80]])
# Get row, col indices
In [87]: row,col = np.diag_indices(arr.shape[0])
# Assign values, let's say from an array to illustrate
In [88]: arr[row,col] = np.array([100,200,300,400,500])
In [89]: arr
Out[89]:
array([[100, 69, 35, 98, 16],
[ 93, 200, 72, 51, 65],
[ 51, 33, 300, 43, 53],
[ 15, 26, 16, 400, 52],
[ 31, 54, 29, 95, 500]])
您还可以使用 np.diag_indices_from
可能会更像偶像,就像这样-
You can also use np.diag_indices_from
and probably would be more idomatic, like so -
row, col = np.diag_indices_from(arr)
注意::尝试过的功能可以正常工作.在先前的问答中也对此进行了讨论- Numpy修改ndarray对角线.
Note : The tried function would work just fine. This is discussed in a previous Q&A - Numpy modify ndarray diagonal too.
这篇关于为每个python numpy用不同的值填充矩阵对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!