MATLAB/Octave Code Generation
Generate MATLAB/GNU Octave simulation scripts with built-in visualization.
Features
Multiple ODE solvers: ode45, ode23, ode15s, ode113, ode23s
Publication-quality plots: Time histories, phase space, energy conservation
Nested function structure: Parameters accessible without globals
CSV export: Automatic results file with energy column
Octave compatible: Works with GNU Octave 5.0+
Basic Usage
from mechanics_dsl.codegen.matlab import MatlabGenerator
import sympy as sp
theta, g, l = sp.symbols('theta g l')
gen = MatlabGenerator(
system_name="pendulum",
coordinates=["theta"],
parameters={"g": 9.81, "l": 1.0},
initial_conditions={"theta": 0.5, "theta_dot": 0.0},
equations={"theta_ddot": -g/l * sp.sin(theta)},
solver="ode45"
)
gen.generate("pendulum.m")
Parameters
solver: MATLAB ODE solver (default:ode45)abstol: Absolute tolerance (default:1e-8)reltol: Relative tolerance (default:1e-6)generate_simulink: Generate Simulink model (default:False)
Supported solvers: ode45, ode23, ode15s, ode113, ode23s
Running in MATLAB
>> results = pendulum();
>> plot(results.t, results.y(:,1));
Running in GNU Octave
octave --eval "pendulum"
Generated Code Structure
The generated .m file contains:
Main function: Configuration, ODE solving, results packaging
``equations_of_motion``: Nested function with parameter access
``compute_energy``: Mechanical energy computation
``plot_results``: Time history subplots saved as PNG
``plot_phase_space``: Phase portrait with start/end markers
``plot_energy``: Energy conservation plot with drift annotation
``export_csv``: Results export with header
Output Files
After running, the script produces:
{system_name}_time_history.png— Position and velocity plots{system_name}_phase_space.png— Phase portrait{system_name}_energy.png— Energy conservation{system_name}_results.csv— Numerical results
Solver Selection Guide
Solver |
Best For |
|---|---|
|
General non-stiff problems (default) |
|
Crude tolerances, fast evaluation |
|
Stiff systems |
|
High accuracy, smooth problems |
|
Stiff with constant mass matrix |
See Also
Julia Code Generation - Julia with DifferentialEquations.jl
Python Code Generation - NumPy-accelerated Python
Code Generation Overview - All code generation targets