How can I access the value of a signal in Simulink during simulation from the MATLAB base workspace?

28 views (last 30 days)
I am using MATLAB to programmatically run a Simulink simulation. 
​This is my code:
model = gcs; open_system(model); set_param(model,'StopTime','Inf'); set_param(model,'SimulationCommand','start');
I would like to access the value of a Simulink signal via the MATLAB base workspace while the simulation is running.
How can I access the value of a specific Simulink signal via the MATLAB base workspace in real-time?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 5 Apr 2025 at 0:00
Edited: MathWorks Support Team on 5 Apr 2025 at 20:49
You can use a MATLAB Function block in Simulink with the "assigin" function to write the value of a signal to the MATLAB base workspace during runtime:
  1. Connect the input of the MATLAB Function block to the output of the signal you want to access, and ensure the output of the MATLAB Function block continues along the original signal path.
  2. The body of the MATLAB function block should contain the following code, where "data" is the name of the signal being written to the base workspace:
    function y = fcn(u)
    coder.extrinsic('assignin')
    assignin('base','data',u)
    y = u;
For an example of how this MATLAB Function block would be placed in a Simulink model to access a signal's value during runtime, please see the screenshots below:

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!