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.
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.
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) add_line(sys,'Int1/1','Int2/1','autorouting','on') pos = [(x+offset*2) y+offset (x+offset*2)+w (y+offset)+h]; add_block('built-in/Scope',[sys '/Scope1'],'Position',pos) add_line(sys,'Int1/1','Scope1/1','autorouting','on')
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_block('built-in/Outport',[sys '/Out1'],'Position',pos) add_line(sys,'Int1/1','Out1/1')
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
72 CommentsOldest to Newest
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.
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.
@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!
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.
@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.
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!
@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.
@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!
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!
@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!
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!
@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:
@Guy, thank you for the promt reply and link.
@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!
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?
@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:
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′)”.
@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!
Seth – I would like your advice on using systems for rapid prototype development.
i have a question that can m-file code dump into input port in simulink model?
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?
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.
I apologize for my previous post. You can find information on how to connect SimPowerSystems blocks here:
Thank you very much indeed.
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.
can i assign signal names of the lines composed in a vector by naming the vector directly.
wil be looking for answers eagerly.
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!
is there a command helpful to add a branch line from a signal in simulink.
i.e, one signal to many blocks.
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″.
way back in the good old days of R13 there was the
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.
thank you verymuch for your nice tutorial
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.
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.
@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!
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?
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.
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.
Thanks Seth, this is great and it just saved me a ton of time and effort.
@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!
I want construct stateflow(inside chart: state, transition, Junction like…….) model from m script.
is it possible?
Yes it is possible. This section of the documentation will teach you how:
Thanks(Nantree in Tamil Language) Guy Rouleau.
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?………
I am expecting your reply………I thing you are too busy….
I want to track my transition action from default transition to end active transition while running the model.
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.
@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.
Taking your suggestion, I will design my model using subsytem in hierarchial manner.
Thanks for prompt reply.
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.
I am trying to generate it using the model construction commands…
how to ‘fitSystem to Display’ in simulink dynamically.it is option available in View Menu of Simulink Model.
@Snehal – I use the Space Bar to fit the system to view.
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?
@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?
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??
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.
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.
@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.
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:
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 – The solution I came up with is
where sbh is the SrcBlockHandle in the source block.
Is there a way to rotate a block with a command out of the command window, so the model looks more well-arranged?
@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,…
Hope this helps!
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.)
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?
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.
@Henning – You can update the label of a line object by using SET_PARAM(h,’Name’,'My Custom Label Name’). Good luck!
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..
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?
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.
how to add masked blocks in the m-file? how to get the block name of masked blocks like eg. Bernoulli Binary Generator???
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???
Can we do the allignment of ports and blocks automatically in the subsystem ?
It’s amazing in support of me to have a web page,
which is good designed for my know-how. thanks admin