There are several ways to make Simulink use variables that you specify inside a function without placing them in the base workspace. A few of them are listed below.
1. Use a "Simulink.SimulationInput" object
The command "sim" accepts objects of the type "Simulink.SimulationInput". You can use a SimulationInput object to temporarily change your model and specify parameters, variables, initial state, etc.
To set a variable, use function "setVariable". For example, to simulate model "f14" with variable "Beta" as 100:
modelname = "f14";
simIn = Simulink.SimulationInput(modelname);
simIn = setVariable(simIn,'Beta',100);
sim(simIn);
If you have a large number of variables to change in your model, you might particularly like the "loadVariablesFromMATFile" function, which as the name implies, loads variables from a MAT file. Alternatively, you can loop the call to 'setVariable' like it is done with 'assignin' in the next option.
The object "Simulink.SimulationInput" is documented here: https://www.mathworks.com/help/simulink/slref/simulink.simulationinput-class.html
The function "setVariable" is documented here: https://www.mathworks.com/help/simulink/slref/simulink.simulationinput.setvariable.html
The function "loadVariablesFromMATFile" is documented here: https://www.mathworks.com/help/simulink/slref/simulink.simulationinput.loadvariablesfrommatfile.html
2. Change the Model Workspace
Each Simulink model is provided with its own workspace for storing variable values, and that takes precedence over the base workspace. You can change the model workspace from your function, or change the MAT-file that is the data source for the model workspace.
This code shows how to programmatically add the functions' variables to the model workspace:
hws = get_param(modelname, 'modelworkspace');
a = 5;
list = whos;
N = length(list);
for i = 1:N
hws.assignin(list(i).name,eval(list(i).name));
end
You can find more information here: https://www.mathworks.com/help/simulink/ug/using-model-workspaces.html
3. Work with Simulink Data Dictionaries
Your model can use variables from a Simulink Data Dictionary. As with the Model Workspace, you can programmatically change the Data Dictionary used by the Simulink model, or even create a new Data Dictionary to replace an old one.
More information about using Data Dictionaries programmatically is located here: https://www.mathworks.com/help/simulink/ug/store-data-in-dictionary-programmatically.html
4. Use 'SrcWorkspace'
This option is not recommended after release R2009b.
The Name-Value option 'SrcWorkspace' can change the workspace used by the model. Use
simOut = sim( modelname, 'SrcWorkspace', 'current')
or set it as an option with 'simset':
options = simset('SrcWorkspace','current');
sim('modelname',[],options)
For information on how to create variables in the base workspace from inside a function, visit the URL: