Tune Parameter Structures with 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 (Simulink)).

In this example, the initial model xpcosc has four parameters that among them determine the shape of the output waveform.

BlockParameterStructure Field ExpressionInitial Value

Signal Generator

Freq

spkp.sg_freq

20

Gain

Gain

spkp.g_gain

1000^2

Gain1

Gain

spkp.g1_gain

2*0.2*1000

Gain2

Gain

spkp.g2_gain

1000^2

Create Parameter Structure

  1. Open model xpcosc and save a copy to a working folder.

  2. 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
    
  3. 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

Replace Block Parameters with Parameter Structure Fields

  1. In the Signal Generator block, replace the value of parameter Frequency with spkp.sg_freq.

  2. In the Gain block, replace the value of parameter Gain with spkp.g_gain.

  3. In the Gain1 block, replace the value of parameter Gain with spkp.g1_gain.

  4. In the Gain2 block, replace the value of parameter Gain with spkp.g2_gain.

Tune Parameters in a Parameter Structure

  1. Build and download the model to the target computer.

    rtwbuild('xpcosc');
    tg = slrt('TargetPC1');
    load(tg,'xpcosc');
  2. Set stop time to inf.

    tg.StopTime = inf;
  3. Sweep the Gain value of the Gain1 block from 200 to 800.

    start(tg);
    for g = 200 : 200 : 800
        setparam(tg, 'spkp.g1_gain', g);
        pause(1);
    end
    stop(tg);
  4. Plot the results.

    time = tg.TimeLog;
    output = tg.OutputLog;
    plot(time, output);

Save and Load Parameter Structure

To save the parameter structure spkp for later use, type:

save 'ex_slrt_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 (Simulink).

Related Topics