Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I provide input to a Simulink model without placing it in the workspace

I have a Simulink model that is currently being run from a script (i.e. not a function). The script writes variable values to the MATLAB workspace, runs the model simulation (which uses these values), and then the model writes additional values to the workspace. If I try to convert the script into a function (i.e. by placing function [output] = runSim() at the top of the file) then Simulink complains that it doesn't know about the variables, presumably because they are not in the MATLAB workspace, but rather they are in the function scope.

Is there an elegant way to provide a Simulink model with inputs and take outputs from a Simulink model other than sticking them into the workspace?

like image 988
JnBrymn Avatar asked Mar 11 '11 22:03

JnBrymn


2 Answers

It's not obvious, but you can input/output data from the sim() command and a calling function's workspace. I've done it before & have an example at work but can't get there until Monday to verify. However, try the solution listed on Mathworks's site:

Solution:

When using variable mask parameters in Simulink, the base workspace is the default source workspace of Simulink. However, by using the SIMSET command, this workspace can be changed. SIM is then used with this options structure created by SIMSET. The following is an example on how to do this.

  options = simset('SrcWorkspace','current');
  sim('modelname',[],options)

...although apparently this got deprecated in R2009b due to incompatibility with the Parallel Computing Toolbox >:( Looks like the correct solution is to explicitly push variables into the simulation's model workspace (different than the base workspace), using assignin().

http://www.mathworks.com/matlabcentral/newsreader/view_thread/292544

You have 2 options:

  1. For releases before R2009b, look at the SIMSET documentation. It allows you to set the "SrcWorkspace" property to "current" to use the data from your function.

http://www.mathworks.com/support/solutions/en/data/1-1BWDA/?solution=1-1BWDA

  1. In newer releases, this option is deprecated because it is not compliant with the Parallel Computing Toolbox and PARFOR. What I recommend is:

http://www.mathworks.com/support/solutions/en/data/1-ASPEIV/?solution=1-ASPEIV

like image 126
Jason S Avatar answered Sep 23 '22 06:09

Jason S


You can use the evalin() function to execute from your own function a MATLAB expression (as a string) in a specific workspace, in your case the 'base' for SIMULINK to find them. However, if you do not want to use the workspace directly then you can load and save the signals or variables from/to MAT files using the From/To File blocks.

like image 28
Mahmoud Kassem Avatar answered Sep 26 '22 06:09

Mahmoud Kassem