I am building a Simulink model with Matlab Function
blocks. These function blocks have a lot of constants, for example g=9.8
. I want to initialize all of these constants in one go in a Matlab script, so that I don't have to do so in each function block.
Here's what I have tried until now:
Matlab Function
block I have initialized the variables using a Constant
block, which is given as a input to the function block. This system works, but there are a lot of constant blocks in the model and it's getting very clustered. I have also tried declaring these variables as global
variables in the Matlab script. This does not work.
Another way that I have tried is so to create a function script for these constants and then load this function script in the Matlab Function
block. This does not work.
Is there a way that I can just initialize these values from the Matlab script and the Simulink model reads it from the Matlab script, without me having to use these constant blocks?
%refercode
%matlabscript
Initialization values;
sim('filenmae.slx');
post processing;
%simulink model
constant blocks(initialization values) -> matlab function block -> output;
%end
What's the best way to solve this problem?
You could have a single struct containing your variables, which can be selectively used in your Matlab Function
blocks. This means you can just have a single Constant
block and additional function input, intialized from your script.
This MathWorks article shows how you can convert the struct into a Simulink Bus for use in your model (you can't use the struct in a constant block directly):
https://blogs.mathworks.com/simulink/2011/12/05/initializing-buses-using-a-matlab-structure/
Giving you something like this:
% initialise constants within struct, keeps the workspace tidy too!
vars = struct();
vars.g = 9.8;
vars.lambda = 2;
% Create bus data for the variables struct
varsInfo = Simulink.Bus.createObject(vars);
% Sim the model
sim( 'myModel.slx' );
With your constant block configured for the bus as described in the linked article:
Then you can access this within your function
function y = ( y, vars )
% MATLAB Function block function within myModel.slx
y = vars.lambda + u * vars.g;