This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Programmatic Modeling Basics

You can perform most Simulink® modeling basics programmatically at the MATLAB® command prompt. The commands that correspond to basic modeling operations, such as creating models, adding blocks to models, and setting parameters, are listed in the Functions section of Interactive Model Editing. These examples show some of these commands and how you can use them.

Load a Model

Loading a model brings it into memory but does not open it in the Simulink Editor for editing. After you load a model, you can work with it programmatically. You can use the Simulink Editor to edit the model only if you open the model.

To load a system, use the load_system command. For example, to load the vdp model, at the MATLAB command prompt, enter:

load_system('vdp')

Create a Model and Specify Parameter Settings

You can write a function that creates a model and uses the settings that you prefer. For example, this function creates a model that has a green background and uses the ode3 solver:

function new_model(modelname) 
% NEW_MODEL Create a new, empty Simulink model
%    NEW_MODEL('MODELNAME') creates a new model with
%    the name 'MODELNAME'. Without the 'MODELNAME'
%    argument, the new model is named 'my_untitled'.

if nargin == 0 
     modelname = 'my_untitled';
end 

% create and open the model
open_system(new_system(modelname));

% set default screen color
set_param(modelname,'ScreenColor','green');

% set default solver
set_param(modelname,'Solver','ode3');

% save the model
save_system(modelname);

Programmatically Load Variables When Opening a Model

If you assign a variable as a block parameter value, you must define the value of the variable in the model. See Load Variables When Opening a Model. You can define the variable programmatically using the PreloadFcn callback with the set_param function. Use the function in this form:

set_param('mymodel','PreloadFcn','expression')

expression is a MATLAB command or a MATLAB script on your MATLAB search path. This command sets the model PreloadFcn callback to the value that you specify. Save the model to save the setting.

For example, when you define the variables in a MATLAB script loadvar.m for the model modelname.slx, use this command:

set_param('modelname','PreloadFcn','loadvar')
To assign the variable K the value 15, use this command:

set_param('modelname','PreloadFcn','K=15')

After you save the model, the PreloadFcn callback executes when you next open the model.

Programmatically Add and Connect Blocks

This example shows how to use functions to add blocks and connect the blocks programmatically. Once you have added blocks to the model, you use three different approaches to connect them: routed lines, port handles, and port IDs. Routed lines allow you to specify the exact (x,y) coordinates of all connecting line segment endpoints. Port handles and port IDs allow connecting lines to block ports without having to know the port location coordinates.

Create and open a blank model named ‘mymodel’.

Add blocks, including a subsystem block. Use the position array in the set_param function to set the size and position of the blocks. Set the upper left and lower right block corners using (x,y) coordinates.

add_block('simulink/Sources/Sine Wave','mymodel/Sine1');
set_param('mymodel/Sine1','position',[140,80,180,120]);
add_block('simulink/Sources/Pulse Generator','mymodel/Pulse1');
set_param('mymodel/Pulse1','position',[140,200,180,240]);
add_block('simulink/Ports & Subsystems/Subsystem','mymodel/Subsystem1');
set_param('mymodel/Subsystem1','position',[315,120,395,200]);
add_block('simulink/Sinks/Scope','mymodel/Scope1');
set_param('mymodel/Scope1','position',[535,140,575,180]);

Inside Subsystem1, delete the default connection between In1 and Out1. Also, add a second input port by copying and renaming In1 from the block library.

delete_line('mymodel/Subsystem1','In1/1','Out1/1');
add_block('simulink/Sources/In1','mymodel/Subsystem1/In2');

Reposition the internal input and output port blocks inside Subsystem1.

set_param('mymodel/Subsystem1/In1','position',[50,50,90,70]);
set_param('mymodel/Subsystem1/In2','position',[50,130,90,150]);
set_param('mymodel/Subsystem1/Out1','position',[500,80,540,100]);

Insert and position an Add block inside Subsystem1.

add_block('simulink/Math Operations/Add','mymodel/Subsystem1/Add1');
set_param('mymodel/Subsystem1/Add1','position',[250,80,290,120]);

Next, add lines to connect all the blocks in the model. Start by connecting the Sine1 and Pulse1 blocks using routed lines.

Find the (x,y) coordinates of the Sine1 output port.

Sine1_Port = get_param('mymodel/Sine1','PortConnectivity')

Sine1_Port = 

  struct with fields:

        Type: '1'
    Position: [185 100]
    SrcBlock: []
     SrcPort: []
    DstBlock: [1×0 double]
     DstPort: [1×0 double]

get_param shows that the port Position is [185 100].

Find the (x,y) coordinates of the Pulse1 output port.

Pulse1_Port = get_param('mymodel/Pulse1','PortConnectivity')

Pulse1_Port = 

  struct with fields:

        Type: '1'
    Position: [185 220]
    SrcBlock: []
     SrcPort: []
    DstBlock: [1×0 double]
     DstPort: [1×0 double]

get_param shows that the port position is [185 220].

Connect the output of Sine1 to the first input of Subsystem1 using three segments of routed line.

add_line('mymodel', [185 100; 275 100]);
add_line('mymodel', [275 100; 275 140]);
add_line('mymodel', [275 140; 310 140]);

Connect the output of Pulse1 to the second input of Subsystem1 using three segments of routed line.

add_line('mymodel', [185 220; 275 220]);
add_line('mymodel', [275 220; 275 180]);
add_line('mymodel', [275 180; 310 180]);

Use get_param to get the port handles of the blocks being connected. Then use the block port handles to connect the output of Subsystem1 to the input of Scope1.

SubsysPortHandles = get_param('mymodel/Subsystem1','PortHandles');
ScopePortHandles = get_param('mymodel/Scope1','PortHandles');
add_line('mymodel',SubsysPortHandles.Outport(1),...
ScopePortHandles.Inport(1));

Use port names and IDs to connect the Add1 block inside Subsystem1 to the subsystem inputs and outputs. Simulink uses the most direct path to connect the ports.

add_line('mymodel/Subsystem1','In1/1','Add1/1');
add_line('mymodel/Subsystem1','In2/1','Add1/2');
add_line('mymodel/Subsystem1','Add1/1','Out1/1');

Name a Signal Programmatically

  1. Select the block that is the source for the signal line.

  2. Use get_param to assign the port handle of the currently selected block to the variable p. Use get_param to assign the name of the signal line from that port to the variable l. Then set the name of the signal line to 's9'.

p = get_param(gcb,'PortHandles')
l = get_param(p.Outport,'Line')
set_param(l,'Name','s9')

Arrange Model Layouts Automatically

You can use the Simulink.BlockDiagram.arrangeSystem command to lay out your model. This command aligns input blocks on the left, output blocks on the right, and model elements in columns between the inputs and outputs. The command affects only one layer at a time.

You can use the Simulink.BlockDiagram.routeLine command to route existing lines of your model. Routing existing lines improves line route quality and avoids overlaps of a line with other lines and obstacles in the model.

While you can use these commands with any open model, they are particularly useful with models you build programmatically. For an example, see Arrange a Programmatically Populated Model.

Open the Same Model in Multiple Windows

When you open a model, the model appears in a Simulink Editor window. For example, if you have one model open and then you open a second model, the second model appears in a second window.

To open the same model in two Simulink Editor windows, at the MATLAB command prompt, enter the open_system command and use the window argument. For example, if you have the vdp model open, to open another instance of the vdp model, enter:

open_system('vdp','window')

Get a Simulink Identifier

Every block in your model has a Simulink Identifier (SID), a unique and unmodifiable identifier. The SID persists for the lifetime of the object and is saved with a model. If the name of the object changes, the SID stays the same. The SID has the form model_name:number.

Locate Diagram Components Using Simulink Identifiers

A Simulink Identifier (SID) is a unique designation automatically assigned to a Simulink block, model annotation, or Stateflow® object within a Stateflow chart. The SID helps to identify specific instances of these components in your diagram, especially when sharing models between people within a team.

To highlight a component visually within the model, get the SID and use it with the Simulink.ID.hilite function.

The SID has these characteristics:

  • Persistent within the lifetime of a Simulink block, model annotation, or Stateflow object

  • Saved in the model file

  • Remains the same if the block or object name changes

  • Cannot be modified

The SID format is:

model_name:sid_number

  • model_name is the name of the model where the block, annotation, or Stateflow object resides.

  • sid_number is a unique number within the model, assigned by Simulink.

The SID includes additional colons in certain cases, for example on an instance of a block from a user library.

Highlight Block

  1. To open the model vdp, enter vdp at the MATLAB command prompt.

  2. Get the SID of the Mu block.

    Simulink.ID.getSID('vdp/Mu')
    ans =
    
    vdp:4
    
    
  3. Use the SID to highlight the block.

    Simulink.ID.hilite('vdp:4')

    The block appears highlighted in the model:

Highlight Annotation

  1. Open the model vdp.

  2. Select the annotation at the top of the diagram.

  3. Get the annotation object for the selected annotation.

    ann = getSelectedAnnotations('vdp')
    ann =
    
    Simulink.Annotation
    
    
  4. Get the SID of the annotation.

    ann.SIDFullString
    ans =
    
    vdp:13
    
    
  5. Use the SID to highlight the annotation.

    Simulink.ID.hilite('vdp:13')

    The annotation appears highlighted in the model:

Highlight Stateflow Object

  1. Open the model sf_resolve_signal_object.

  2. Get the SID of the Signal Object Chart Stateflow object:

    Simulink.ID.getSID('sf_resolve_signal_object/Signal Object Chart')
    
    ans =
    
    sf_resolve_signal_object:1
    
    

  3. Use the SID to highlight the object.

    Simulink.ID.hilite('sf_resolve_signal_object:1')

    The object appears highlighted in the model.

Specify Colors Programmatically

You can use the set_param command at the MATLAB command line or in a MATLAB program to set parameters that determine the background color of a diagram and the background color and foreground color of diagram elements. The following table summarizes the parameters that control block diagram colors.

ParameterDetermines

ScreenColor

Block diagram background

BackgroundColor

Block and annotation background

ForegroundColor

Block and annotation foreground

Set the color parameter to either a named color or an RGB value.

  • Named color: 'automatic', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'gray', 'lightBlue', 'orange', 'darkGreen'

  • RGB value: '[r,g,b]'

    where r, g, and b are the red, green, and blue components of the color normalized to the range 0.0 to 1.0.

For example, the following command sets the background color of the currently selected system or subsystem to a light green color:

set_param(gcs,'ScreenColor','[0.3, 0.9, 0.5]')

See Also

| | | | | | | | | | | | |

Related Topics