如何求解一组有超过 1 个向量未知的矩阵方程

问题描述 投票:0回答:1

我正在尝试用 python 求解一组方程,如下所示:

X2 - C1*X3 = X1
X3 -k*(X4-C2)*sqrt(X2(1-X2))
AX4 = C3*b

其中X2,X3和X4是未知的N维(N是常数)向量。C1,k,C2是已知的常数标量。b和X1是已知的常数N维向量。A是已知的N * N矩阵。向量乘向量的意思在 Python 中只是“*”。对向量开平方意味着向量中的每个元素都开平方。向量减去标量意味着每个元素减去它。

我在 scipy 中尝试了 fsolve,但它不接受二维输入。我可以使用什么方法来解决这个问题?

python matrix scipy equation
1个回答
0
投票

没问题!如果

X1
是随每一步变化的已知向量,则可以相应地修改目标函数。假设每一步都有一个新向量
X1
,您可以将其作为附加参数传递给目标函数。

参见示例:

import numpy as np
from scipy.optimize import fsolve

# Constants
C1 = 1.0
k = 2.0
C2 = 3.0
C3 = 4.0
b = np.array([1.0, 2.0, 3.0])  # Example N-D vector
A = np.array([[2.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 4.0]])  # Example NN matrix

# Reshape vector variables
def reshape_variables(vars_flat):
    N = len(b)
    X2 = vars_flat[:N]
    X3 = vars_flat[N:2*N]
    X4 = vars_flat[2*N:]
    return X2, X3, X4

# Objective function
def equations(vars_flat, X1):
    X2, X3, X4 = reshape_variables(vars_flat)

    eq1 = X2 - C1*X3 - X1  # X2 - C1*X3 = X1
    eq2 = X3 - k*(X4 - C2)*np.sqrt(X2*(1 - X2))  # X3 - k*(X4-C2)*sqrt(X2(1-X2)) = 0
    eq3 = A @ X4 - C3*b  # AX4 = C3*b

    return np.concatenate((eq1, eq2, eq3))

# Initial guess
initial_guess = np.ones(3 * len(b))

# Example X1 vector (replace this with your actual X1)
X1_example = np.array([0.1, 0.2, 0.3])

# Solve the system of equations
solution = fsolve(equations, initial_guess, args=(X1_example,))

# Reshape the solution to get X2, X3, X4
X2, X3, X4 = reshape_variables(solution)

print("Solution:")
print("X2:", X2)
print("X3:", X3)
print("X4:", X4)

现在,

equations
函数将
X1
作为附加参数,您可以为每个步骤传递不同的
X1
向量。根据您的需要调整示例
X1
向量。

© www.soinside.com 2019 - 2024. All rights reserved.