从MATLAB转Python新手:如何在Python中求解符号方程组?
Hey there! As someone moving from MATLAB to Python, SymPy is exactly your go-to tool for symbolic equation solving—it's Python's equivalent of MATLAB's Symbolic Math Toolbox. Let's break down how to replicate your MATLAB workflow step by step, with code that's easy to follow.
Step 1: Import SymPy & Define Symbolic Variables
First, we'll set up SymPy and define all the symbolic coefficients and variables you're working with:
import sympy as sp # Define coefficients and symbolic variables a1, a2, a3 = sp.symbols('a1 a2 a3') x1, x2, x3, x4, x5, x6 = sp.symbols('x1 x2 x3 x4 x5 x6') y1, y2, y3, y4, y5, y6 = sp.symbols('y1 y2 y3 y4 y5 y6')
Step 2: Translate Your Equations to SymPy Format
Unlike MATLAB, SymPy works with scalar equations rather than direct matrix equalities, so we'll expand your matrix conditions into individual equations. Here's how to map your MATLAB equations:
# Build the full system of equations equations = [ # From a1*[x1; x2] == [y1; y2] sp.Eq(a1 * x1, y1), sp.Eq(a1 * x2, y2), # From a2*[x3; x4] == [y3; y4] sp.Eq(a2 * x3, y3), sp.Eq(a2 * x4, y4), # From a3*[x5; x6] == [y5; y6] sp.Eq(a3 * x5, y5), sp.Eq(a3 * x6, y6), # The linking conditions between variables sp.Eq(x2, y3), sp.Eq(x3, y2), sp.Eq(x4, y5), sp.Eq(x5, y4) ]
Step 3: Solve the System & Extract Simplified Results
Next, we'll use SymPy's solve() function to find solutions for your specified unknowns. We'll request results in dictionary format to make extracting variables straightforward:
# Specify the unknown variables you want to solve for unknowns = [x2, x3, x4, x5, y1, y2, y3, y4, y5, y6] # Solve the system (returns a list of solution dictionaries) solution = sp.solve(equations, unknowns, dict=True) # Extract and simplify your desired outputs (note: assuming y10 was a typo—your equations only include y1-y6, so we'll use y6 here) y1_simplified = sp.simplify(solution[0][y1]) y6_simplified = sp.simplify(solution[0][y6]) # Print the clean results print("Simplified y1:", y1_simplified) print("Simplified y6:", y6_simplified)
Quick Tips for MATLAB Users
- SymPy uses
sp.Eq()to define equality equations (instead of MATLAB's direct==insidesolve()). - The
solve()function returns a list of dictionaries—since your system should have a unique solution, we grab the first entrysolution[0]. sp.simplify()behaves just like MATLAB'ssimplify()to tidy up symbolic expressions.
内容的提问来源于stack exchange,提问作者sun0727




