gpt4 book ai didi

python - 如何解决 “ValueError: expected square matrix”问题?

转载 作者:行者123 更新时间:2023-12-03 08:32:20 26 4
gpt4 key购买 nike

我将使用LU分解来求解线性方程Ax = b。当我将此代码用于较小的矩阵时,该代码很好用,但是当我输入较大的矩阵时,它不起作用。相反,它说:

Traceback (most recent call last):
File "main.py", line 18, in <module>
LU = linalg.lu_factor(A)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/scipy/linalg/decomp_lu.py", line 76, in lu_factor
raise ValueError('expected square matrix')
ValueError: expected square matrix
在这里您可以查看我的代码:
import pprint
import scipy
import math

#import linalg package of the SciPy module for the LU decomp
import scipy.linalg as linalg

#import NumPy
import numpy as np

#define A same as before
A = np.array([[math.sin(45), 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [-(math.sin(45)), 0, -1, 1, math.sin(45), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [0, 0, 0, 0, -(math.sin(45)), 0, 1, 0, math.sin(45), 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, -(math.sin(45)), 0, -1, 0, math.sin(45), 0, 0, 0, 0 ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ,0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, -1, math.sin(45), 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -(math.sin(45)), 0, 1, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -(math.sin(45)), -1]])

#define B
B = np.array([0, 0, 10, 0, 15, 0, 0, 0, 10, 0])

#call the lu_factor function
LU = linalg.lu_factor(A)


#solve given LU and B
x = linalg.lu_solve(LU, B)

print ("Solutions:\n",x)

#now we want to see how A has been factorized, P is the so called Permutation matrix
P, L, U = scipy.linalg.lu(A)

print ("P:")
pprint.pprint(P)

print ("L:")
pprint.pprint(L)

print ("U:")
pprint.pprint(U)
谢谢! :)

最佳答案

this solver用于非方阵:

scipy.sparse.linalg.lsqr(A, b, damp=0.0, atol=1e-08, btol=1e-08, conlim=100000000.0, iter_lim=None, show=False, calc_var=False, x0=None)
找到大型稀疏线性方程组的最小二乘解。
该函数求解Ax = b或最小值|| Ax-b || ^ 2或最小值|| Ax-b || ^ 2 + d ^ 2 || x || ^ 2。
矩阵A可以是正方形或矩形的(过高或过低),并且可以具有任何等级。

关于python - 如何解决 “ValueError: expected square matrix”问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65710411/

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