gpt4 book ai didi

python - 在 3D numpy 数组中填充对角线

转载 作者:行者123 更新时间:2023-12-05 03:27:35 30 4
gpt4 key购买 nike

给定 3D arr,我想填充所有等于 1 的 dioganal 元素。

np.random.seed(0)
arr=np.random.rand(3,4,4)

预期产出

1,0.71519,0.60276,0.54488
0.42365,1,0.43759,0.89177
0.96366,0.38344,1,0.52889
0.56804,0.92560,0.07104,1



1,0.83262,0.77816,0.87001
0.97862,1,0.46148,0.78053
0.11827,0.63992,1,0.94467
0.52185,0.41466,0.26456,1



1,0.56843,0.01879,0.61764
0.61210,1,0.94375,0.68182
0.35951,0.43703,1,0.06023
0.66677,0.67064,0.21038,1

如下分配fill_diagonal

arr=np.fill_diagonal(arr, 1)

返回一个错误

ValueError: All dimensions of input must be of equal length

我可以知道如何正确填充 3d 数组的对角线等于 1

到目前为止正在尝试什么

arr[:,:,0] = np.diag((1,1))

ValueError: could not broadcast input array from shape (2,2) intoshape (3,4)

应避免什么

使用 for-loopfill_diagonal

最佳答案

试试这个:

r = np.arange(4)
arr[:, r, r] = 1

例子:

arr = np.arange(3*4*4).reshape(3,4,4)
r = np.arange(4)
arr[:, r, r] = 1

输出:

array([[[ 1,  1,  2,  3],
[ 4, 1, 6, 7],
[ 8, 9, 1, 11],
[12, 13, 14, 1]],

[[ 1, 17, 18, 19],
[20, 1, 22, 23],
[24, 25, 1, 27],
[28, 29, 30, 1]],

[[ 1, 33, 34, 35],
[36, 1, 38, 39],
[40, 41, 1, 43],
[44, 45, 46, 1]]])

关于python - 在 3D numpy 数组中填充对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71434639/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com