Main Content

Programmatic Modeling Basics

You can perform most Simulink® modeling basics programmatically at the MATLAB® Command Window, such as creating models, adding blocks to models, and setting parameters. 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, suppose you have a model named myModel on the MATLAB path. To load the model, enter this command in the MATLAB Command Window:

load_system('myModel')

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. 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');

Programmatically Comment Out or Comment Through Blocks

To view or change the commented state of a block programmatically, use the get_param and set_param commands.

  • To view the commented state of a block:

    get_param(gcb,'commented');

  • To comment out a block:

    set_param(gcb,'commented','on');

  • To comment through a block:

    set_param(gcb,'commented','through');

  • To uncomment a block:

    set_param(gcb,'commented','off');

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 handle of the line connected to 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 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 a model called modelName open, to open another instance of modelName, enter:

open_system('modelName','window')

Use Model Finder to Index and Search Models and Improve Their Discoverability

You can use the modelfinder function to search examples, models, and projects in multiple databases. By default, modelfinder searches the MathWorks® Examples database. You can also configure your databases with Model Finder. For more information on Model Finder, see Configure and Search Databases.

Locate Diagram Elements Using Highlighting

To highlight a block, line, port, or annotation in an open model, use hilite_system.

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 model colors.

ParameterDetermines

ScreenColor

Model 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