如何在Python中求解矩阵方程组?

时间:2019-05-07 21:05:21

标签: python matrix system equation

我必须解矩阵方程组 如: 变量(矩阵):X1,X2,X3,X4,X5 常数(矩阵):其他

X1 = R *(A + B X2 + D X3 + D X4 + E X5)

X2 = R_2 *(A + B X1 + C X3 + D X4 + E X5)

X3 = R_3 *(A + B X1 + C X2 + D X4 + E X5)

X4 = R_4 *(A + B X1 + C X3 + D X2 + E X5)

X5 = R_5 *(A + B X1 + C X2 + D X3 + E X4)

我可以使用任何可用的函数或库来求解此方程吗? (我试图安装puLp,但是我没有安装纸浆;它不起作用)

对于Matlab,我猜它太慢了。

1 个答案:

答案 0 :(得分:0)

您的系统不是以方便的方式编写的。您应该在一侧常量 隔离,在另一侧变量。 我做到了:

+      X1 - R1*B*X2 - R1*D*X3 - R1*D*X4 - R1*E*X5 = R1*A
- R2*B*X1 +      X2 - R2*C*X3 - R2*D*X4 - R2*E*X5 = R2*A
- R3*B*X1 - R3*C*X2 +      X3 - R3*D*X4 - R3*E*X5 = R3*A
- R4*B*X1 - R4*D*X2 - R4*C*X3 +      X4 - R4*E*X5 = R4*A
- R5*B*X1 - R5*C*X2 - R5*D*X3 - R5*E*X4 +      X5 = R5*A

我建议您再做一次检查...

完成后,您可以使用 numpy 来解决它,如下所示:

# Import numpy
import numpy as np 

# Define each constant ...
R1 = R2 = R3 = R4 = R5 = 1
A = B = C = D = E = 1

# Define each row of the system :
# Here, because of the 'R' factor and the symetry, I found
# quite faster doing like this :
row1 = R1*np.array([1, -B, -D, -D, -E])
row2 = R2*np.array([-B,  1, -C, -D, -E])
row3 = R3*np.array([-B, -C,  1, -D, -E])
row4 = R4*np.array([-B, -D, -C,  1, -E])
row5 = R5*np.array([-B, -C, -D, -E,  1])

# Create the matrix
mat = np.array([row1, row2, row3, row4, row5])

# The diagonal is equal to 1
for i in range(len(mat)):
    mat[i,i] = 1

# Define the constant side
constant = A*np.array([R1, R2, R3, R4, R5])

# Resolve it !
res = np.linalg.solve(mat, constant)
print(res)