Python 如何求解一组有 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是已知的常数N维向量。A是已知的N * N矩阵。向量乘法向量意味着简单的' * ' 在 Python 中。对向量开平方意味着向量中的每个元素都开平方。向量减去标量意味着每个元素减去它。

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

python matrix scipy equation
1个回答
0
投票

如果

fsolve
不直接接受 2 维输入,您可以将 N 维向量展平为 1 维数组,并在目标函数内重塑它们。这是一个例子:

import numpy as np
from scipy.optimize import fsolve

# Constants
N = 3  # Replace with your actual N value
C1 = 2
k = 0.5
C2 = 1
C3 = 3
b = np.array([1, 2, 3])  # Example N-D vector
A = np.array([[2, 0, 0], [0, 1, 0], [0, 0, 3]])  # Example NN matrix

# Reshape function
def reshape_solution(vars):
    return vars.reshape((N, -1))

# System of equations
def equations(vars):
    X = reshape_solution(vars)
    X2, X3, X4 = X

    eq1 = X2 - C1 * X3 - X[0]
    eq2 = X3 - k * (X4 - C2) * np.sqrt(X2 * (1 - X2))
    eq3 = np.dot(A, X4) - C3 * b

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

# Initial guess
initial_guess = np.zeros(N * 3)

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

# Reshape the solution
X2, X3, X4 = reshape_solution(solution)

# Print the results
print("X2:", X2)
print("X3:", X3)
print("X4:", X4)

这应该适用于

fsolve
,即使它只接受一维输入。
reshape_solution
函数用于将展平向量重塑回原始 N 维向量。将常数和矩阵替换为您的实际值。

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