Guy on Simulink

Simulink & Model-Based Design

Building Models with MATLAB Code 75

Posted by Seth Popinchalk,

Occasionally I get questions about how to build, modify, and add blocks, to Simulink models using MATLAB commands. In this post, I will to give a basic overview of the common model construction commands.


Start With a New System

Because you need to refer to the system so often when doing model construction from M-code, I immediately save that off in a variable called sys. The new_system command created the empty model in memory, and you have to call open_system to display it on-screen.

sys = 'testModel';
new_system(sys) % Create the model
open_system(sys) % Open the model

Adding Blocks and Lines

When I add blocks to the canvas, I specify the position to provide proper layout. The position parameter provides the top left (x,y) and lower right (x+w,y+h) corners of the block. The x and y values are relative to the origin (0,0) in the upper left corner of the canvas; x increases to the right, and y increases down. To keep my layout organized, I use a standard blocks size of 30 by 30, and offsets of 60.

x = 30;
y = 30;
w = 30;
h = 30;
offset = 60;

I like my ports with slightly different proportions, so I define them to be half the height of the other blocks. add_block specifies the source block and the destination path, which defines the block name. Block names must be unique for a given system so add_block provides a MakeNameUnique option. (not used here)

pos = [x y+h/4 x+w y+h*.75];
add_block('built-in/Inport',[sys '/In1'],'Position',pos);

I'll add an integrator block, offset to the right of the inport.

pos = [(x+offset) y (x+offset)+w y+h];
add_block('built-in/Integrator',[sys '/Int1'],'Position',pos)

To connect the blocks, call add_line and provide the system name, source port and destination port. The ports are designated by the 'blockname/PortNum' format. Default line routing is a direct line connection from the source to destination. I prefer to use the autorouting option.


When adding multiple blocks and lines, I group them into add_block/add_line pairs to keep myself organized.

pos = [(x+offset*2) y (x+offset*2)+w y+h];
add_block('built-in/Integrator',[sys '/Int2'],'Position',pos)

pos = [(x+offset*2) y+offset (x+offset*2)+w (y+offset)+h];
add_block('built-in/Scope',[sys '/Scope1'],'Position',pos)

Deleting Blocks and Lines

When deleting blocks, I call delete_line before delete_block. This is the reverse of what I did before. The commands are grouped in delete_line/delete_block pairs. For this example, I'll delete the integrator Int2, and add an outport.

delete_block([sys '/Int2'])

pos = [(x+offset*2) y+h/4 (x+offset*2)+w y+h*.75];
add_block('built-in/Outport',[sys '/Out1'],'Position',pos)

Replacing Blocks

Sometimes you don't really want to delete a block, you are just going to replace it. replace_block gives you the capability to replace all blocks that match a specific criteria. I reccommend carefully reading the documentation to better understand this function.

set_param([sys '/In1'],'Position',[x y x+w y+h],'Name','Sine Wave');

[t,x,y] = sim(sys);
plot(t,y), ylim([-.5 2.5]), grid on

Now it's your turn

Do you use model construction commands? Why doesn't the cosine on that scope cross below zero? Leave a comment here with your thoughts.

Get the MATLAB code

Published with MATLAB® 7.9

75 CommentsOldest to Newest

Bob replied on : 1 of 75

Yes, I’ve used the model construction commands.

Occasionally to build up models.

More interestingly to use MATLAB and library blocks with the option turned on to modify contents to populate the block based on mask parameters. Amazing what one can do that way, I’ve been able to avoid writing S-Functions with the approach.

I’ve occasionally needed to replace blocks, but never quite had replace_block work. Problems having lines reconnect with more than one inport/outport. Problems because dialog parameters need to be transformed for the new block.

Jim replied on : 2 of 75

I have done this extensively. I’ve also used commands to create/populate Stateflow flowcharts.

One great use I’ve found is to automatically connect multiple component models into a complete system model. Once the script works, for large models this approach is much faster and much more accurate than connecting ports by hand.

Seth replied on : 3 of 75

@Bob – I like you example of using self modifying blocks in place of S-functions. I find REPLACE_BLOCK is a really powerful tool for updating models that might use an obsolete utility block.

@Jim – I have never written code to connect up large system models into components, but I have seen the results. This is when auto line routing can really improves the look of the diagram.

Thanks for your comments!

Aleksandar replied on : 4 of 75

Seth, thank you very much!

I have additional question. Is it possible to alter Simulink model built into executable? I need a way for changing Simulink model on machine where I have only Matlab Runtime Environment.

Seth replied on : 5 of 75

@Aleksandar – If you build a Simulink model into an executable using Real-Time Workshop, you will only be able to modify the run-time parameters of the model. Using the Rapid Simulation Target (RSIM), you can use RSIMGETRTP to get a run-time parameter structure. This can be modified in MATLAB, saved to a MAT-file and passed into your executable as an argument. Look at the Accelerated Simulations Demos in Real-Time Workshop for examples of how to do this.

If your goal is to modify the MDL file and use the SIM command to run it, that will not work in a deployed MATLAB application.

Marko replied on : 6 of 75

Hi, Seth! Thank you for your advices!
I have one question, but I am not sure is this right address for it. Anyway, I’ve been working in SimPowerSystems for a short period of time. I would like to know is there any possibility of speeding up a simulation, since any model I have run seems to work in a real time. To be more specific, I would like to model how much energy (power KWh) would wind turbine produce in a year, using some of prefabricated models inside SimPowerSys. So, if I put that time (365*24*3600) in the simulation, it seems it would work for a month.
Thank you very much, I would appreciate your answer very much!

Guy replied on : 7 of 75

@Marko – Simulink include Accelerator and Rapid Accelerator modes which can help speeding up models. However in your case I am not sure this is the appropriate option.

You probably noticed that SimPowerSystems include Wind Farm demos implemented in two ways: detailled and average. For most applications, I recommend having a detailled model to study the transitional dynamics of the system over a short period of time. For the long term you want an average model which will skip details but will run fast.

Marko replied on : 8 of 75

@Guy – Thank you for you effort, but as far as accelerators are concerned ,they compile model into c code and than use some techniques to accelerate the model, but in my application that is not very suitable.

Regarding those average models, you will notice that both detailed and average are run for 0.2 sec in approximately same speed (I have put for ex. 100 sec for simulation time, it seems to run forever). However, I was wondering if there is any model that could be run for much longer time.

Thank you anyway!

Marko replied on : 9 of 75

Thank you all for comments!

I am trying to deploy a model on a web. To do so, first I have to build a model using RTW, but when I try to build it, it shows me following message:

Algebraic loops are not supported in generated code. Use the ‘ashow’ command in the Simulink Debugger to see the algebraic loops.

I started with very simple model, which has a loop. I desperately need to work this through. Is there any alternative solution for this? I would be very grateful for any answer! Thank you!

Mark replied on : 11 of 75

Seth, thank you very much for this post!

I have additional question. Is it possible to rotate/flip blocks with model construction commands? Thank you!

Guy replied on : 12 of 75

@Mark, Rotate anf flip can be done using set_param(gcb,’orientation’,’right’) where you can replace ‘right’ by ‘left’, ‘up’,’down’.

Marko replied on : 14 of 75

@Seth, I want to thank you on your valuable comment and I would appreciate if you could tell me if Real-Time Workshop is going to support that functionality (“generate code for models that contain algebraic loops”) in future releases.
Thank you very much again!

Jesus replied on : 15 of 75

Thanks for your post on Simulink model construction commands, but where could we obtain the commands for Simscape models. I infer it uses the same commands, but how can they be parametrized? Could you give us some examples?

Guy replied on : 16 of 75

@Jesus – Construction commands are not fully supported for Simscape blocks. For example ADD_BLOCK works fine, but the way to use ADD_LINE is not documented and consequently not supported.

Based on experience, I use set_param with Simscape blocks only to set the value of some dialog parameters, for example to set the resistance of a Resistor block you can do “set_param(gcb,’R’,’100′)”.

Seth replied on : 17 of 75

@Marko – As you know, algebraic loop solving is an iterative process and doesn’t guarantee a solution. It is also not appropriate within an embedded system without some kind of control for performance.

I have heard other requests for support to generate code from models that contain algebraic loops, but these are generally in the context of rapid simulation/batch simulation.

I wonder if your situation is the same? I have passed this on to our developers to consider for a future release. Thanks!

Hadi Ariakia replied on : 20 of 75

Hi Seth
Thanks a lot, it is really useful.

I’ve a question regarding the add_line, delete_line etc.
I have to always use power Sim, but I cannot use delete_line for deleting lines between some models.For example, I cannot delete lines connecting two “distributed parameters line” models, or I can delete or add line to/from the most of ports of “Three-phase V-I measurement” model.
I’ve tried all the below commands:

delete_line('Ps_circuit','Section 2/1','Section 3/1')
delete_line('Ps_circuit','Section 2/1','Section 3/1')
delete_line('Ps_circuit','Three-Phase V-I Measurement1/3','Section 1/1')

Whilst the command works for some ports such as Three-Phase V-I Measurement1/1 !
Actually, it returns error messages such as “Invalid Simulink object name: Three-Phase V-I Measurement1/3.”

Could you please give some idea what the problem is?


Guy replied on : 21 of 75

Hi Hadi,

Please see my post above. Construction commands like add_line and delete_line are not documented and consequently not supported for physical signals, including SimPowerSystems.

For these blocks, you will be able to use add_line for simulink ports, but not for physical ports.


raju replied on : 24 of 75

thank you seth and others discussed here.

can you help me in reading the propagated signal names of the vector muxed with n lines one by one through a code.

raju replied on : 25 of 75

can i assign signal names of the lines composed in a vector by naming the vector directly.

wil be looking for answers eagerly.
please help

tong replied on : 26 of 75

I have just installed the MATLAB2010.But in the simulink part,the block of Embedded MATLAB fuction can not be used.
It always said’the block can’t be found’.However, the other blocks of User-Defined Fuctions can be used.
So please give me a hand.Thank you!

Rajshekar replied on : 27 of 75

is there a command helpful to add a branch line from a signal in simulink.
i.e, one signal to many blocks.

Guy replied on : 28 of 75


ADD_LINE can be used for that. For example:


will first connect “Constant” with “Display1”. The second line will branch out from the line just created and finally “Constant” will be connected to both “Display1” and “Display2”.


Jörg replied on : 29 of 75

way back in the good old days of R13 there was the

save_as(..., 'm')

command. Given a model, it could write an m-script, that when executed, let the model reappear “by magic” (nowadays this works for figures only).

In this spirit, I’d like to know, whether there is something like a “macro recorder” in Simulink: Switch it on, tell it where to store the result and start to draw your model. I expect it to record all my gestures and moves with the mouse and the keyboard as model construction commands … and after stopping the recording, we get that model-constructing m-file. No typing, no calculation. Edit the resulting m-file to polish it according to your needs.

Is there such a feature in Simulink? I could not find it.

Thomas replied on : 31 of 75


In 2007b, it is possible. Reminder, Matlab is Case Sensitive
I tried :
add_block(‘simulink/User-Defined Functions/Embedded MATLAB Function’,’untitled/Embedded’)
and it works.

It’s a bit more complex to fill though.

Emile replied on : 32 of 75

Hi Seth,

Thanks a million for this great tutorial. This is exactly what I needed. First I tried doing this with the




commands, but this is WAY easier. Fixed in a minute, what I was trying to do for the last half an hour!

BTW, in response of your question: The cosine comes out of the integrator, which has initial condition zero, which explains why the signal does not cross zero.


Seth replied on : 33 of 75

@Emile – I’m glad it worked! I’m also glad to see you noticed why the Cosine doesn’t cross zero! You are the first to respond to that question. THANKS!

Sneha replied on : 34 of 75

My name is Sneha.
I have following question.
I have two subsystems at the top most level in model and the first subsystem has 2 output ports and the second one has two input ports.
I want to join outputs of first to inputs of second by add_line. But I am getting an error ‘??? Error using ==> add_line. Invalid Simulink object specifier.’ for the second command in the following commands
I tried to add line as follows:
Is this approch correct?
Can you suggest me a solution?

Zohaib replied on : 35 of 75

Hi everyone,

Is there a way to connect two ports based on their port names rather than numbers?

For instance I have in System A I have a port named A_port and in System B I have a port named B_port. I want to connect them based on their names, NOT the port numbers.



vahid replied on : 36 of 75

Hello Seth,
I’m a master student of electrical engineering. I want to work at controlling of wind turbines with matlab/simulink.
I wiil be so thanlful if you help me at this major.
Best regards

Seth Popinchalk replied on : 38 of 75

@Sneha – I’m not sure why it isn’t working. Make sure the block names are exactly the same. You can select the block, then type


to see what the block name is.

@Zohaib – Connecting by name is not available in the ADD_LINE function, but it is pretty easy to accomplish with a few lines of code. Get the port names of the subsystems, and the port numbers, then search for matches. When a match is found, connect those ports.

@Joe Heinrichs – I am glad you found this post!

M Hakkeem replied on : 39 of 75

I want construct stateflow(inside chart: state, transition, Junction like…….) model from m script.
is it possible?

M Hakkeem replied on : 42 of 75


I want to track my transition action from default transition to end active transition while running the model.

Can we do this? and How Can do?………

M Hakkeem replied on : 44 of 75

I want to track my transition action from default transition to end active transition while running the model.

chandan replied on : 45 of 75

Good tutorial!

I am constructing a big model from matlab code.
It involves around 2000 blocks. I need to set position of these blocks.

What is the limitation on ‘Position’ parameter? I want to know what are boundary values for positioning blocks.

Seth Popinchalk replied on : 46 of 75

@Chandan – The limit for a Model window coordinate is 32768, BUT I strongly reccomend keeping them within the limits of your screen. Subsystems and model reference hierachy make models much easier to work with. Every time I have seen a Simulink model that looks like an Eye-exam-chart, there have been problems lurking… often simple things like unconnected lines, or extra blocks. Those kind of errors can drive you nuts and models that your can’t easily browse will drive you insane when debugging.

chandan replied on : 47 of 75

Taking your suggestion, I will design my model using subsytem in hierarchial manner.
Thanks for prompt reply.

Dhiraj replied on : 48 of 75

It was great to go thru the post and the discussions.
I was trying to generate the subsystem of the model I have constructed and make it an s-function for my next model. I just couldnot make it, If anyone have tried and or done, would be of great help to be informed.

Snehal replied on : 50 of 75

how to ‘fitSystem to Display’ in simulink is option available in View Menu of Simulink Model.

Wintersprite replied on : 52 of 75

Gentlemen, your posts are great and touch on odd topics that are not explained so well in the documentation. You never answered the guy last year who wondered whether there was any possibility of a “model construction recording mode,” like recording a macro in Excel. You would record everything as you built the model, and then it could generate the corresponding m-script from it. What are the prospects for this?

Guy Rouleau replied on : 53 of 75

@Wintersprite: This is a good point. Currently, MathWorks does not provide such feature. However, you are not the first person asking for that. Our development team is aware of this and considering it.

Can you let us know a bit more details on your use case? Why this feature would be useful for you?

Sriharsha replied on : 54 of 75


i have an application where i need to create a subsystem using a GUI.

I have a model with a gain block and a filter block , followed by a scope, where my input is a sine wave.

Now i need to create a subsystem , in which i should include the gain and filter blocks into it (subsystem).

I need to do this using GUI.

The implementation flow is like:

I should select blocks and then i need to click a button on GUI, and then a subsystem should be created in place of blocks.

Can any one please help me in doing this??


Sriharsha S

Wintersprite replied on : 55 of 75

Gentlemen, I have learned a lot since I inquired further about the keystroke recording in Simulink. I thought it would be useful for an application where I need to first have a bunch of display scopes present, and then remove them. I thought this repetitive operation could be learned in a macro so I didn’t have to write the script. But then I got to wondering about a different method of removing lines, and now I have colored all the lines to be removed every time as green, and learned how to select and delete all the green lines and blocks with about four lines of script. But one thing I could still use advice on is where to find a complete list of line properties, because I could really extend the utility of this script by knowing more about the line properties.

Sobhi replied on : 56 of 75


Is there a way you can replace a subsystem from one model with a subsystem from a differnet model keeping all the connections after you replace it? I am trying to do this in M script.


Seth replied on : 57 of 75

@Sobhi – I think the function you are looking for is replace_block. Try using the full path to the subsystem (‘model/Block_name’) for your new_blk value.

K replied on : 58 of 75

In continuation to @Hadi(20)/Guy(22),

I’ve managed to connect physical ports using the add_line documnetation Guy provided. It’s when I try to delete lines connecting physical ports that I get errors.

I’ve tryied the following command:
>>> delete_line(sys,hblk(2,i).RConn,hblk(4,i).RConn);

and got the following error
??? Invalid line specifier.

1. Is it possible to delete lines connecting physical ports using the delete_line() function?
2. If so, how exactly?


K replied on : 59 of 75

@K – The solution I came up with is


where sbh is the SrcBlockHandle in the source block.

Merle replied on : 60 of 75

Is there a way to rotate a block with a command out of the command window, so the model looks more well-arranged?

Patrick replied on : 61 of 75

@Merie I use the block parameters blockRotation, orientation, and position to make my models look clean. If you use the get_param function on a block that you have set up by hand you can find out the exact settings for that block and add them to your add_block code.


% Start by adding a desired block to an empty system and stretching, positioning and rotating until content. Then use these three lines below to find out the parameters.

blk_rot = get_param([path ‘/blkName’],’BlockRotation’)
blk_O = get_param([path ‘/blkName’],’Orientation’)
blk_pos = get_param([path ‘/blkName’],’Position’)

% Now that you have those parameters either hard code them into your add_block code or make them variables in your code for easy changes. one other option if you want to just change an existing blocks looks you can simply use set_param function.

add_block(‘blk_library’,[path ‘/blkName’],… ‘MakeNameUnique’,’on’,’position’,pos,’BlockRotation’,180,…

% or

set_param([path ‘/blkName’],’BlockRotation’,’blk_rot’);
set_param([path ‘/blkName’],’Orientation’,’blk_O’);
set_param([path ‘/blkName’],’Position’,’blk_pos’);

Hope this helps!

samy replied on : 62 of 75

I am having a problem with the 3 phase V-I measurement connected to one terminal of the generator and its other terminal rectified then connected to a D.C load(also the same problem when the generator is unloaded).
the error is (Input two of Voltage Measurement block ‘SEIG/Three-Phase V-I Measurement/Model/VI/Va’ is not properly connected to the network.)

Quang replied on : 63 of 75

Hello guys,

Let’s say I have two blocks A and B that are connected by a signal. I would like to copy A, B AND the signal to some subsystem in the SAME model using Matlab APIs. Any ideas?

Henning replied on : 64 of 75


how can I change the “signal name” of a line, after insert it with ADD_LINE?

I would create a bus with “Bus Creator” which needs the signal name.

Seth replied on : 65 of 75

@Henning – You can update the label of a line object by using SET_PARAM(h,’Name’,’My Custom Label Name’). Good luck!

ashwani replied on : 66 of 75

hello guys
i have designed a dfig and i m facing problem in connecting it to the grid and the power converter device,just because of lack connectivity of connection port with any signal in my dfig block, and thats why the square connection ports will not formed on the boundry of the sub system, i hope u will definetly provide me some relevant solution of this problem..

Chiara replied on : 67 of 75

I am using R2010a.
I have to ask you two things.

1) I am building a model by command lines and, although I know functions to get/set block position, I would like script to place blocks automatically, avoiding to have blocks too close to each other.

2) When I add a block that already exists, I know how to change name so that it’s unique, but is there a way to avoid that the new block appears on the old one?

Thank you

chitra replied on : 68 of 75

hello sir, i am getting algebraic loops are not supported in generated code. i have added the unit delay block in feedback path but again i am getting this error. so please tell the solution for this. but this works good while simulating and not while running on beagle board.

olinda replied on : 69 of 75


how to add masked blocks in the m-file? how to get the block name of masked blocks like eg. Bernoulli Binary Generator???

Thank you

olinda replied on : 70 of 75

also i have tried this command line but it works for only Built-in blocks. what is the syntax for the blocks which are not Built-in, like Bernoulli Binary Generator, Interleaver, CRC Generator, Modulator, etc? and how to find the name of the block to be used in the syntax for blocks which are not Built-in???

Koushik Sarkar replied on : 72 of 75

I have started to build model of radial distribution feeder in SIMULINK. Do I need to write my code in MATLAB script first and then develop the model? If anyone with similar experience can help me or provide link of writing code with developing the model, and with a demo, it will be appreciated.

Mohan replied on : 73 of 75


Am pretty new to Matlab programming and am trying to generate Simulink model using Matlab code and am currently trying to implement Simulink sub systems. I want to add multiple sub Systems, one after another, to a simulink model and want to able to increment the Name of the Sub System like (eg.: SubSystem1, SubSystem2…..and so on).

Currently I am using the following code:

pos2 = [200 50 500 200];
add_block(‘built-in/SubSystem’, ‘TestModel/SubSystem’, ‘Position’, pos2);

So would like to know how I could increment the Sub System value while having this code inside a “for” Loop.

Any help will be appriciated!

Best Regards

Ravi replied on : 74 of 75

I’m using a variable from workspace in simulink and downloaded that model in arduino.if the value of the variable got changed, I should re-download the model to the hardware…is there any way to automatically update this value??

saqib replied on : 75 of 75


I am trying to generate models from .m file with the following code:

block_label = strcat(fname, ‘/V1’);
add_block(‘powerlib/Electrical Sources/Three-Phase Source’, block_label,…
‘Position’, [140 95 170 125],…
% Add a gain block, setting the gain value to 2
block_label2 = strcat(fname, ‘/M1’);
add_block(‘powerlib/Measurements/Three-Phase V-I Measurement’, block_label2,…
‘Position’,[240 95 270 125]);
%port_name = strcat(block_label, ‘/1’);
%port_name2 = strcat(block_label2, ‘/1’);
% Connect the sine and the gain

But it gives me an error- Invalid Simulink object name: V1

Can you suggest me something?

Add A Comment

Your email address will not be published. Required fields are marked *


Preview: hide