gpt4 book ai didi

python - 在没有numpy的情况下更改对角线方阵 - Python

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:21 27 4
gpt4 key购买 nike

我有一些数据:

values = [2.1254,0.0125,1.3542,0.2543]
residuals = [0.0251,0.0005,0.1223,0.0043]

然后我创建了一个矩阵:

matrix = [[i] * len(values) for i in values]

现在我想将残差向量加到矩阵的对角线上。我试过:

def fc(x)
for i in range(len(values)):
x[i][i] + residuals[i]

但我不知道如何返回结果。

print(fc(matrix))

返回

这是所需的矩阵:

matrix1 = [[2.1505,2.1254,2.1254,2.1254],
[0.0125,0.013,0.0125,0.0125,
[1.3542,1.3542,1.4765,1.3542]
[0.2543,0.2543,0.2543,0.2586]]

最佳答案

这是使用列表理解和枚举的一种方式:

values = [2.1254,0.0125,1.3542,0.2543]
residuals = [0.0251,0.0005,0.1223,0.0043]

def fc(values, residuals):
n = len(values)
res = [[i]*n for i in values]
for idx, j in enumerate(residuals):
res[idx][idx] += j
return res

res = fc(values, residuals)

结果:

[[2.1505, 2.1254, 2.1254, 2.1254],
[0.0125, 0.013, 0.0125, 0.0125],
[1.3542, 1.3542, 1.4765, 1.3542],
[0.2543, 0.2543, 0.2543, 0.2586]]

关于python - 在没有numpy的情况下更改对角线方阵 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49959038/

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