Tune Parameter Structures by Using MATLAB Language
To reduce the number of workspace variables you must maintain and avoid name conflicts, you can group closely related parameters into structures. See Organize Related Block Parameter Definitions in Structures.
In this example, the initial model slrt_ex_osc
has four parameters that
determine the shape of the output waveform.
Block | Parameter | Structure Field Expression | Initial Value |
---|---|---|---|
| Freq |
|
|
| Gain |
|
|
| Gain |
|
|
| Gain |
|
|
Create Parameter Structure
This procedure groups some closely related parameters into structures.
Open model
slrt_ex_osc
and save a copy to a working folder.To create a parameter structure, in the MATLAB® Command Window, enter:
kp = struct(... 'sg_freq', 20, ... 'g2_gain',1000^2, ... 'g1_gain', 2*0.2*1000, ... 'g_gain',1000^2)
kp = struct with fields: sg_freq: 20 g2_gain: 1000000 g1_gain: 400 g_gain: 1000000
To make the parameter structure tunable on the target computer:
spkp = Simulink.Parameter(kp); spkp.StorageClass = 'ExportedGlobal'; spkp.Value
ans = struct with fields: sg_freq: 20 g2_gain: 1000000 g1_gain: 400 g_gain: 1000000
Save and Load Parameter Structure
To save the parameter structure spkp
for later use, type:
save 'slrt_ex_osc_struct.mat', 'spkp'
To load the parameter structure when you open the model, add a
load
command to the PreLoadFcn
callback. To
remove the parameter structure from the workspace when you close the model, add a
clear
command to the CloseFcn
callback. For
more information, see Model Callbacks.
Replace Block Parameters with Parameter Structure Fields
In the
Signal Generator
block, replace the value of parameter Frequency withspkp.sg_freq
.In the
Gain
block, replace the value of parameter Gain withspkp.g_gain
.In the
Gain1
block, replace the value of parameter Gain withspkp.g1_gain
.In the
Gain2
block, replace the value of parameter Gain withspkp.g2_gain
.
Tune Parameters in a Parameter Structure
If you have not completed the steps in Create Parameter Structure, Replace Block Parameters with Parameter Structure Fields, and Save and Load Parameter Structure, you can start by using the completed model.
To open the model, in the MATLAB Command Window, type:
open_system(fullfile(matlabroot, 'toolbox', 'slrealtime', ... 'examples', 'slrt_ex_osc_struct')); load(fullfile(matlabroot, 'toolbox', 'slrealtime', ... 'examples', 'slrt_ex_osc_struct.mat'));
Build and download the model to the target computer.
slbuild('slrt_ex_osc_struct'); tg = slrealtime('TargetPC1'); load(tg,'slrt_ex_osc_struct');
Set stop time to
inf
.setStopTime(tg,inf);
Sweep the
Gain
value of theGain1
block from200
to800
.start(tg); for g = 200 : 200 : 800 setparam(tg, '', 'spkp.g1_gain', g); pause(1); end stop(tg);
View the signals sent to the Scope block in the Simulation Data Inspector.
Simulink.sdi.view;