0
0
MatlabHow-ToBeginner ยท 3 min read

How to Run Simulation in Simulink in MATLAB: Step-by-Step Guide

To run a simulation in Simulink from MATLAB, use the sim('modelname') command where modelname is your Simulink model file without the extension. This command starts the simulation and returns the simulation output data.
๐Ÿ“

Syntax

The basic syntax to run a Simulink simulation from MATLAB is:

  • sim('modelname'): Runs the simulation of the Simulink model named modelname.
  • simOut = sim('modelname'): Runs the simulation and stores output data in simOut.
  • sim('modelname', 'StopTime', '10'): Runs the simulation and stops at 10 seconds.

Replace modelname with your actual Simulink model file name (without .slx or .mdl extension).

matlab
sim('modelname')
simOut = sim('modelname')
sim('modelname', 'StopTime', '10')
๐Ÿ’ป

Example

This example shows how to load a Simulink model, run its simulation for 5 seconds, and plot the output signal.

matlab
load_system('sldemo_signal_generator')
simOut = sim('sldemo_signal_generator', 'StopTime', '5');

% Extract output signal from simulation output
signal = simOut.get('yout');

% Plot the signal
plot(signal.time, signal.signals.values)
title('Simulink Signal Generator Output')
xlabel('Time (seconds)')
ylabel('Signal Amplitude')
โš ๏ธ

Common Pitfalls

  • Model name errors: Forgetting to remove the .slx or .mdl extension causes errors.
  • Model not loaded: The model must be loaded or on MATLAB path before running sim.
  • Stop time as string: Stop time must be a string, e.g., '10', not a number.
  • Output variable missing: If you don't capture output, you can't access simulation results.

Wrong: sim('model.slx')
Right: sim('model')

matlab
sim('model.slx') % Wrong: includes extension
sim('model')    % Correct: no extension
๐Ÿ“Š

Quick Reference

Remember these quick tips when running Simulink simulations from MATLAB:

  • Use sim('modelname') without file extension.
  • Load model first with load_system('modelname') if needed.
  • Set simulation stop time as a string, e.g., '10'.
  • Capture output with simOut = sim(...) to analyze results.
  • Use simOut.get('yout') to access logged signals.
โœ…

Key Takeaways

Use sim('modelname') without file extension to run Simulink simulations from MATLAB.
Always load the model or ensure it is on the MATLAB path before simulating.
Pass stop time as a string, e.g., '10', to control simulation duration.
Capture simulation output in a variable to access and analyze results.
Avoid including file extensions in the model name to prevent errors.