Search code examples
matlabsimulink

Run Simulink from Matlab function


I am running Simulink using FastRestart, as I need to start and stop the simulation multiple times changing parameters. When I run Simulink from the main script, there are no problems. However, as soon as I make the script a function so that I can run it for different input data, I get an error that is clearly related to Simulink not seeing the Matlab workspace within the function.

To be more precise, say sfile is my Simulink file, then I run the following lines AFTER having initialized all variables I need in structures in Matlab:

load_system(sfile);
set_param(sfile,'FastRestart','on');
set_param(sfile,'SaveFinalState','on');
set_param(sfile,'SaveCompleteFinalSimState','on');
set_param(sfile,'SimulationCommand','update');

At the last line, I get the error that Simulink does not recognize mdl.tStep (which is the time step), as mdl is not a recognized structure. In fact, it is and if I run Simulink from the main script everything is fine.

Now, in the past, I would have used

options = simset('SrcWorkspace','current');

However, an expert I know has advised me against simset (as it may get deprecated in the future) and encouraged me to use set_param instead. I have looked up the options for set_param on-line, but I could not find the setting for the Matlab workspace.

Any help would be greatly appreciated. Thank you in advance!


Solution

  • A solution to your problem might be to use the assignin-function to all the variable whose value you want to pass to simulink in your matlab base workspace. To do so just use

    assignin('base','mdl',mdl)
    

    Having the variable in your base workspace should allow simulink to see it.