How to Run Simulink Models from MATLAB Script Easily
You can run a Simulink model from a MATLAB script using the
sim('modelName') command, where modelName is the name of your Simulink model file without the extension. This command starts the simulation and returns simulation results that you can use for further analysis.Syntax
The basic syntax to run a Simulink model from a MATLAB script is:
sim('modelName'): Runs the Simulink model namedmodelName.simOut = sim('modelName'): Runs the model and stores simulation output insimOut.sim('modelName', 'StopTime', '10'): Runs the model and sets the stop time to 10 seconds.
Replace modelName with your actual Simulink model file name without the .slx extension.
matlab
sim('modelName') simOut = sim('modelName') sim('modelName', 'StopTime', '10')
Example
This example shows how to run a Simulink model named simple_model from a MATLAB script and get the simulation output.
matlab
model = 'simple_model'; load_system(model); % Load the model into memory simOut = sim(model, 'StopTime', '5'); % Run simulation for 5 seconds % Access simulation output (assuming model has output logged as 'yout') y = simOut.get('yout'); % Display first few values of output disp(y(1:5,:)); close_system(model, 0); % Close model without saving
Output
[0.0000 0.0000]
0.5000 0.1000
0.9800 0.1960
1.4400 0.2880
1.8700 0.3740
Common Pitfalls
- Model not loaded: Forgetting to load the model with
load_systemcan cause errors. - Wrong model name: Using the file name with extension or a wrong name will fail.
- Output not logged: If the model does not log output signals,
simOut.getwill return empty. - Simulation parameters: Not setting parameters like
StopTimemay run the model indefinitely or with default settings.
matlab
%% Wrong way: Using file name with extension sim('simple_model.slx') % This causes error %% Right way: Use model name without extension sim('simple_model')
Quick Reference
Here is a quick summary of commands to run Simulink models from MATLAB scripts:
| Command | Description |
|---|---|
| sim('modelName') | Run the Simulink model named 'modelName' |
| simOut = sim('modelName') | Run model and save output to variable |
| sim('modelName', 'StopTime', '10') | Run model with stop time set to 10 seconds |
| load_system('modelName') | Load model into memory without opening GUI |
| close_system('modelName', 0) | Close model without saving changes |
Key Takeaways
Use sim('modelName') to run a Simulink model from a MATLAB script.
Always use the model name without the .slx extension in the sim command.
Load the model with load_system before simulating for better control.
Set simulation parameters like StopTime to control simulation duration.
Access simulation results from the output object returned by sim.