繁体   English   中英

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

[英]How to solve the problem of "ValueError: expected square matrix"?

我将使用 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) 

谢谢: :)

将此求解器用于非方阵:

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)

找到大型、稀疏、线性方程组的最小二乘解。

function 求解 Ax = b 或 min ||Ax - b||^2 或 min ||Ax - b||^2 + d^2 ||x||^2。

矩阵 A 可以是正方形或矩形(超定或欠定),并且可以具有任意秩。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM