# Initializing Parameters34

Posted by Seth Popinchalk,

Simulink models often use parameters from the MATLAB base workspace.  However, Simulink does not save the MATLAB base workspace with the model.  This leads me to the following question: How do you initialize the workspace for your simulation?

Most Simulink Demos initialize the base workspace before they are loaded.  Let’s take a look at f14.mdl:

In the F14 model, you see gain blocks with parameters like Zw, Mw, Mq and 1/Uo.  Simulink evaluates those MATLAB expressions in the base workspace during initialization of the simulation.

You can register model callbacks that run when you perform different actions on the model.  In this example, f14.mdl has a PreLoadFcn that runs a script to initializes the workspace.  You can see the model callbacks by opening the Model Properties from the File menu.

The model pre-load function executes before the model is actually loaded.  If you only need to initialize a few variables for your model, you can enter the MATLAB expressions directly in the pre-load function callback.  The F14 model calls the M-file script f14dat.m.

If I am tweaking variables in my model, I like to change them directly in the workspace browser, or at the command line.  The pre-load function is a good place for initializing variables because it only runs the first time the model is loaded.  This allows you to change the variables for the current session without modifying the initialization code.

Other techniques for initialization?

Farid Arvani replied on : 1 of 34

Instead of creating an script and loading it with the model using PreLoadFcn, one can easily use the Model Explorer. Press Ctrl+H. It will open the Model Explorer. In the model hierarchy pane on the left, you see Base Workspace which is the main Matlab Workspace that is normally used like the method above.
You can also see Model Workspace under each open simulink model hierarchy. This is the workspace that is used only by that model. By using this workspace, you will keep Matlab workspace clean and furthermore you do not have to carry the model file (.mdl) and an initialization file (.m or .mat) around. To benefit from this feature, change data source combo on the very right pane to M-code. Input your initializations there and save your model. That’s it. From now on whenever you open the model file, it will load the defined variables into its private workspace and you will not see any mess in Matlab workspace.
I have to add that this method is good for one-time initializations since you will not be able to change the variables from workspace; again Model explorer should be used for any variable modifications.

Cheers
Farid

Rachid replied on : 2 of 34

hello

I have a model with many blocs, the last have also the blocs and parameters, so i want to get all these parameters, make them in struct and respect the path of any blocs and parameters
so there are the function who do this?

Hossein replied on : 3 of 34

alberto cardeñoso replied on : 4 of 34

Hello,
what about initialisation with Simulinks models where a Simulation Settings block is present? One example is the IEEE® 802.11a WLAN Physical Layer Simulink Demo. How does it works?

Thanks.
Alberto.

Seth replied on : 5 of 34

@alberto cardeñoso – Thanks for your question. These kinds of blocks are usually just masked subsystems. Try right clicking on the blocks and selecting, “Edit Mask”. If you look at the MaskInitialization code you can find that it just runs a script. To see the content of that script,

>> edit commwlan80211a_settings;


The code in the script performs a few get_param commands then assigns a variable into the base workspace. This model is carefully constructed so that all those variables are accessed from the blocks in the model. Double click on the blocks to see how.

alberto cardeñoso replied on : 6 of 34

Hello,
thank you Seth for your answer. I have written one script like this,

function initialisation1

% Parameter settings for the simulation
%

% Fist of all fetch parameters from the Adjust Settings block
%
% Construct the whole name of the block
settings_block = [bdroot ‘/’ settings_block_name];

[data_rate, …
modulation, …
channel_type,…
SNR,…
rolloff] = …
get_settings(settings_block,…
‘data_rate’,…
‘modulation’,…
‘channel_type’,…
‘SNR’,…
‘rolloff’);

% Data Source, Sample Time and Frame Time
p.data_rate = data_rate; % Data rate.

% Modulations Squeme
p.modulation = modulation; % Selected modulation squeme: BPSK, QPSK, 8-PSK …

p.rolloff = rolloff; % Roll-off factor of the transmit and receive filters.

% Channel parameters
p.channel_type = channel_type; % Channel Type: AWGN, Rayleigh, Rice …
p.SNR = SNR; % SNR of the channel.

assignin(‘base’,’parameters’,p);

%————————————————————————-

function varargout=get_settings(settings_block,varargin)

h=get_param(settings_block,’handle’); % Get the handle of the block.
for n=1:length(varargin)
varargout{n}=evalin(‘base’, get(h,varargin{n}));
end

I don´t know why, but the get_settings function is not working. There is a problem with the
evalin function. The initialisation1 function is called from the mask initialisation of the “Settings Block”,
as well as from the PostLoadFcn from the Model.

Any idea?

THanks
Alberto

Seth replied on : 7 of 34

@Alberto – I think you should set a break point in the function, and when you hit that point, you can step through the code to see what is the problem. Note, your initialization code doesn’t have to be this complicated. In fact, you may want to build a MATLAB GUI using GUIDE and replace the OpenFcn for a subsystem. Good luck.

I think you will get a faster answer from Technical Support or on CSSM.

Muhammad Arsalan replied on : 8 of 34

Hi Seth,

I am facing a very interesting problem about the parameter dependencies.
The problem is that i have to use some parameters which are dependent on other parameters. e.g.
x = 6 and y = [0, x, 10, 15, x/2]
Now when these parameters are loaded to the base workspace of MATLAB the dependency of y on x is lost. In base workspace the value of y is taken as [0, 6, 10, 15, 3]. By this depencency lose it is not possible to change the values in y when it is used in model, just by changing the x. Is there any way by which this lose of dependency is avoided.

Thank you very much indeed.
Arsalan

Seth replied on : 9 of 34

@Muhammad Arsalan – you have brought up an interesting problem. It would be possible to tune parameters while the simulation is running (or paused) and keep them consistent. I would use a cell in my script that initialized X and Y, then execute just that cell to update the values in the MATLAB workspace. You can then update the diagram (Ctrl-D) to get the new values into the simulation.

The relationship between these variables will not be automatically recognized in generated code. For that you will need to consider custom storage classes where you can layout the X memory as part of Y. This will ensure consistency.

Anyone else have a suggestion?

wei replied on : 10 of 34

@Seth,
I’m interested to see how the dependence of y on x is managed through memory layout. To me this should be part of model done diagrammatically.

Seth replied on : 11 of 34

@wei – I overlooked the X/2 expression. That cannot be managed through memory layout. It might be possible to create a Data Store that holds X, and diagramatically create Y (Stored in a Data Store) based on X. Then when X and Y are used, the relationship would be correct (as long as execution of the blocks is grouped as an atomic unit).

ziera replied on : 12 of 34
a = magic(3);
sum(a)


sir, i have problem..can u help me?

ziera replied on : 13 of 34

dear sir, i have the same like this demo. my model have many blocks, gain and also include some coding (embedded matlab function)..but sir, i dont know how to put my initialization parameter coding like your coding in the last figure..


Seth replied on : 14 of 34

@ziera – The file in the last figure is a MATLAB script on the MATLAB path. You could create something similar in your current directory. To start creating a MATLAB file (.m), type:

>> edit

DG replied on : 15 of 34

Seth,
I am setting simulink variables, such as stop time, gain values in a GUI m-file. However these variables are no longer in the simulink workspace when the simulink model starts, e.g. t_stop, etc. Perhaps I could try the technique above using PreLoadFnc but am not sure how to write this m-file when the variables are updated.
Is there an easier way around this?

Seth replied on : 16 of 34

@DG – I have seen this challenge with other GUI programming problems. Ultimately, you need to place the variable where Simulink will find it. If you are executing a callback from a MATLAB GUI, you can use ASSIGNIN to put the variable into the MATLAB base workspace. This will be found by your Simulink model. If you actually want to put the variables into the model workspace, read through the doc on Using Model Workspaces. If you are running the model with the SIM command from inside the GUI, check the doc for your version to see how best to pass the parameters into the function.

Jonathan replied on : 17 of 34

Seth,

I have a subsystem that I want to have initialized from an input port value.

i.e set the Buffer block, output buffer size. So it has to initialize the value before the simulation starts.

Is there any way of doing this? I can run a get_param() on a Constant block on InitFcn and set a variable in the Matlab Workspace, but I was hoping to be able to keep this initialization within the sub-system. Do you have any suggestions?

Seth replied on : 18 of 34

@Jonathan – in the case of the Buffer block, you can not use the result calculated in one part of the model to set the buffer size. The buffer size affects the dimensions of the output signal. Dimensions and memory allocations have to be finalized during update diagram, before the simulation runs, outputs from other blocks are not available. It sounds like the algorithm you are trying to build varies the memory requirements (signal widths) based on a parameter input. If this is a constant, I suggest using a workspace variable or Simulink.Parameter, referenced from the blocks that rely on it.

If the parameter is not constant and signal width changes during the simulation, I recommend you evaluate the R2010a pre-release new features.

Ghodrat Esmaeili replied on : 19 of 34

Thanks for all the good stuff you guys are posting here.

Joel replied on : 20 of 34

I am writing a my own filter in simulink. And at present I am using the memory blocks provided by simulink. However I wish to convert to writing my own piece of code which will act like a memory block. It will be an array that acts like a FIFO buffer.

However to do this the array needs to be initialised in Simulink somehow so that it can be written to.
I only want to do this as a once off. But what ever i try so far hasn’t worked.

Any Ideas. Thanks
Joel

Sudha B replied on : 21 of 34

Seth,
Im working on the inbuilt Matlab simulink model of 802.11a for my project work.The sampling rate for this model is 20 MHz and is fixed.Can you please help me,how to change the sampling rate for this inbuilt model?

Anna F replied on : 22 of 34

Hi Seth,

Are there any extra settings in the model that have to be configured in order for this initialization to work? I appear to have done everything you said, however I keep getting an error in my model that tells me the workspace variable I’m trying to load does not exist (and checking the workspace, it never loads). I’m accessing a variable “x” which I define in a script(I’ll call the file “xi.m”), and my preload function calls this script (and yes, I remembered to just put xi in the preload). I am attempting to access the variable x through a constant block, and when I already have the variable in the workspace, it works just fine, its just the preload that isn’t working for me. Do you have any suggestions for something I could tweak to make it work?

Thanks!
–Anna

siva replied on : 23 of 34

I have a problem in passing the parameters values from a function to simulink. CAN ANYBODY HELP ME?

SIVA

Seth Popinchalk replied on : 25 of 34

@siva – Your question might be better posted on the new Q&A site at MATLAB Central. Go to MATLAB Central and click on Answers. Be sure to tag your question with “Simulink”. Good luck!

krishna replied on : 26 of 34

Hi,
There is a variation in simulation results by passing the parameter values from script file to simulink blocks (PID controller)against the direct values assignment for the PID controller.CAN ANYBODY TELL ME THE REASON?

Seth replied on : 27 of 34

@krishna – there should be no difference in answers as long as the values are the same. I’m not sure by which method you are “passing the parameter values from script file to simulink blocks.” Do you mean you call a set_param command? Are you creating variables in the workspace (P=1, I=.01, D=0) and assigning those variables in the block dialog?

krishna replied on : 28 of 34

Hi seth,
I have created the variables in workspace and assigning those variables in block dialog(simulink,PID controller block)versus directly assigning the numerical values in the PID block dialog.

Divya replied on : 29 of 34

Hi Seth,

I am very new to Simulink and am trying to run a Simulink model with many Sub-models. I am getting an error saying “Configuration reference ‘CommonConfiguration’ specifies configuration set ‘CommonConfiguration’ that does not resolve to a variable in the base workspace”. May I know how I can rectify the same?

Thanks,
Divya

mchennu replied on : 30 of 34

Hi,

Is it possible to set up the current directory and preload the variables inside that directory before running the model using preloadfcn?

Thanks,
chennu

Jakub Lisowski replied on : 31 of 34

Hi Seth,

I used to initialize the model parameters via either ‘MAT-File’ or ‘MATLAB-File’. It seemed convenient for large scale models with hundreds of parameters to be stored in easily readable format. However some time ago I encountered this message:

Warning: 'MDL-File' and 'M-Code' are no longer valid values for the
model workspace's DataSource property.  Update your MATLAB code to
use the valid values ('Model File' and 'MATLAB Code') instead.


First of all message is ambiguous, because there are no ‘MDL-File’ and ‘M-Code’ options. ‘MDL-File’ can be understood as ‘Model File’ or if we assume the spelling error – ‘MEX-File’, what is more probable due to the information that ‘Model File’ is to be considered as a valid value. On the same basis I deduced that ‘M-Code’ = ‘MATLAB Code’.
Therefore I have 2 questions to you:

1. Can you clarify the meaning of this warning?

2. If the ‘MAT-File’ and ‘MATLAB-File’ options are the ones which will be removed in future Simulink versions what is the reason behind that? In my opinion these options were actually the most useful initialization techniques. In such case what do you recommend as a workaround?

Thanks,

Jakub

Guy Rouleau replied on : 32 of 34

@Jakub: This is just a syntax change, the capability to specify the data source for the model workspace to be from the model or from MATLAB code remains. The only thing that changes is that in the past, to specify that the data in model workspace was saved with the model, you would programmatically say:

hws = get_param(bdroot,'modelworkspace')
hws.DataSource = 'MDL-File'


Now that Simulink has two file extensions (mdl and slx), it has been decided that the following syntax is more appopriate:

hws = get_param(bdroot,'modelworkspace')
hws.DataSource = 'Model File'
`

The functionality is the same, only the name of the option changed.

Same thing for “M-code”, which now becomes “MATAB Code”.

Mike replied on : 33 of 34

When I have my Model Workspace Data Source set to Matlab File or Matlab Code, I am finding that I need to press “Reinitialize from Source” multiple times before the variables in the workspace are actually updated to reflect the changes I made in the initialization script. Often I have to open the Variable Editor and check that the elements of the struct have actually changed. Two questions:
1. Why am I needing to press Reinitialize multiple times (currently running R2016a)?
2. Opening the Variable Editor is highly inefficient. Is there a way to enable a tree view of struct contents in the Workspace view in Model Explorer without having to open the Variable Editor every time you want to look inside the struct?

Thanks

Guy Rouleau replied on : 34 of 34

@Mike: I agree with you about the visualization of structures in Model Explorer. I brought that up to our development.

About the multiple clicks, this is definitely unexpected. I recommend contacting technical support so we can investigate.

What is 1 + 10?

Preview: hide