# Guy and Seth on Simulink

## Building Models with MATLAB Code

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.

### Contents

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

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.

add_line(sys,'In1/1','Int1/1','autorouting','on')

pos = [(x+offset*2) y (x+offset*2)+w y+h];

pos = [(x+offset*2) y+offset (x+offset*2)+w (y+offset)+h];
add_line(sys,'Int1/1','Scope1/1','autorouting','on')

### 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_line(sys,'Int1/1','Int2/1')
delete_block([sys '/Int2'])

pos = [(x+offset*2) y+h/4 (x+offset*2)+w y+h*.75];
add_line(sys,'Int1/1','Out1/1')

### 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.

replace_block(sys,'Name','In1','built-in/Sin','noprompt');
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

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

### 67 Responses to “Building Models with MATLAB Code”

1. Bob replied on :

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.

2. Jim replied on :

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.

3. Seth replied on :

@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.

4. Aleksandar replied on :

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.

5. Seth replied on :

@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.

6. Marko replied on :

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.

7. Guy replied on :

@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.

8. Marko replied on :

@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!

9. Marko replied on :

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!

10. Seth replied on :

@Marko – Real-Time Workshop doesn’t generate code for models that contain algebraic loops. The only option is to remove them from your model. There is a technical support solution entitled: What are algebraic loops in Simulink and how do I solve them?

I recommend you review that information and see if you can resolve the algebraic loop. Good luck!

11. Mark replied on :

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!

12. Guy replied on :

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

The list of all the common block parameters that can be configured using SET_PARAM can be found here:

13. Mark replied on :

14. Marko replied on :

@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!

15. Jesus replied on :

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?
Thanks

16. Guy replied on :

@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.

It is possible to use set_param and get_param on Simscape blocks, however the following documentation page warns you:

http://www.mathworks.com/access/helpdesk/help/toolbox/physmod/simscape/ug/bqqjdvg-1.html

It mentions that “You can use the Simulink set_param and get_param commands to set or get Simscape block parameters. The MathWorks does not recommend that you use these commands for this purpose.”

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′)”.

17. Seth replied on :

@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!

18. Alex replied on :

Seth – I would like your advice on using systems for rapid prototype development.

19. rajshekhar replied on :

i have a question that can m-file code dump into input port in simulink model?

20. Hadi Ariakia replied on :

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?

Regards,

21. Guy replied on :

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.

Guy

22. Guy replied on :

I apologize for my previous post. You can find information on how to connect SimPowerSystems blocks here:

http://www.mathworks.com/access/helpdesk/help/toolbox/physmod/powersys/ug/f1-32601.html

Guy

Hi Guy
Thank you very much indeed.

24. raju replied on :

hi
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.

25. raju replied on :

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

wil be looking for answers eagerly.

26. tong replied on :

Hello!
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!

27. Rajshekar replied on :

HI,
i.e, one signal to many blocks.

28. Guy replied on :

Rajshekar,

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″.

Guy

29. Jörg replied on :

Seth,
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.

30. pydiraju replied on :

Hi seth,

thank you verymuch for your nice tutorial

pydiraju

31. Thomas replied on :

Tong,

In 2007b, it is possible. Reminder, Matlab is Case Sensitive
I tried :
and it works.

It’s a bit more complex to fill though.

32. Emile replied on :

Hi Seth,

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

get_param

and

set_param

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.

Cheers,
Emile

33. Seth replied on :

@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!

34. Sneha replied on :

Hello,
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?

35. Zohaib replied on :

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.

Thanks,

-Z

36. vahid replied on :

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
vahid

37. Joe Heinrichs replied on :

Thanks Seth, this is great and it just saved me a ton of time and effort.

38. Seth Popinchalk replied on :

@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

gcb

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!

39. M Hakkeem replied on :

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

40. Guy Rouleau replied on :

@M Hakkeem.

Yes it is possible. This section of the documentation will teach you how:

http://www.mathworks.com/help/releases/R2011a/toolbox/stateflow/api/f13-6010.html

41. M Hakkeem replied on :

Thanks(Nantree in Tamil Language) Guy Rouleau.

42. M Hakkeem replied on :

Hi

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?………

43. M Hakkeem replied on :

Hi

Thanks

44. M Hakkeem replied on :

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

45. chandan replied on :

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.

46. Seth Popinchalk replied on :

@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. There is a documentation page dedicated to Simulink Limits here.

47. chandan replied on :

Taking your suggestion, I will design my model using subsytem in hierarchial manner.

48. Dhiraj replied on :

Hi,
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.

49. Dhiraj replied on :

I am trying to generate it using the model construction commands…

50. Snehal replied on :

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

51. Seth replied on :

@Snehal – I use the Space Bar to fit the system to view.

52. Wintersprite replied on :

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?

53. Guy Rouleau replied on :

@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?

54. Sriharsha replied on :

Hi,

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.

Regards

Sriharsha S

55. Wintersprite replied on :

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.

56. Sobhi replied on :

Hello,

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.

Regards,
Sobhi

57. Seth replied on :

@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.

58. K replied on :

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

59. K replied on :

@K – The solution I came up with is

delete_line(find_system(sys,’findall’,'on’,'type’,'line’,'SrcBlockHandle’,sbh))

where sbh is the SrcBlockHandle in the source block.

60. Merle replied on :

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

61. Patrick replied on :

@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.

Example:

% 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.

‘Orientation’,'Right’);

% 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!
-Patrick

62. samy replied on :

Hello,
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.)

63. Quang replied on :

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?

64. Henning replied on :

Hello,

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.

65. Seth replied on :

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

66. ashwani replied on :

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

67. Chiara replied on :

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

 Name (required) E-mail (required, will not be published) Website (optional) Spam protection (required): What is 1 + 2 ?

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>


If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).

Guy Rouleau and Seth Popinchalk are Application Engineers for MathWorks. They write here about Simulink and other MathWorks tools used in Model-Based Design.

These postings are the author's and don't necessarily represent the opinions of MathWorks.