{"id":79,"date":"2010-01-21T05:20:48","date_gmt":"2010-01-21T05:20:48","guid":{"rendered":"https:\/\/blogs.mathworks.com\/seth\/2010\/01\/21\/building-models-with-matlab-code\/"},"modified":"2010-01-21T05:23:56","modified_gmt":"2010-01-21T05:23:56","slug":"building-models-with-matlab-code","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/simulink\/2010\/01\/21\/building-models-with-matlab-code\/","title":{"rendered":"Building Models with MATLAB Code"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Occasionally I get questions about how to build, modify, and add blocks, to Simulink models using MATLAB commands.  In this\r\n         post, I will to give a basic overview of the common <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/bq3cxmi.html#bq3ftt5\">model construction commands<\/a>.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Start With a New System<\/a><\/li>\r\n         <li><a href=\"#3\">Adding Blocks and Lines<\/a><\/li>\r\n         <li><a href=\"#10\">Deleting Blocks and Lines<\/a><\/li>\r\n         <li><a href=\"#12\">Replacing Blocks<\/a><\/li>\r\n         <li><a href=\"#14\">Now it's your turn<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Start With a New System<a name=\"1\"><\/a><\/h3>\r\n   <p>Because you need to refer to the system so often when doing model construction from M-code, I immediately save that off in\r\n      a variable called <tt>sys<\/tt>.  The <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/new_system.html\"><tt>new_system<\/tt><\/a> command created the empty model in memory, and you have to call <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/open_system.html\"><tt>open_system<\/tt><\/a> to display it on-screen.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">sys = <span style=\"color: #A020F0\">'testModel'<\/span>;\r\nnew_system(sys) <span style=\"color: #228B22\">% Create the model<\/span>\r\nopen_system(sys) <span style=\"color: #228B22\">% Open the model<\/span><\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/seth\/2010Q1\/testModelEmpty.png\"> <\/p>\r\n   <h3>Adding Blocks and Lines<a name=\"3\"><\/a><\/h3>\r\n   <p>When I add blocks to the canvas, I specify the position to provide proper layout. The position parameter provides the top\r\n      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\r\n      left corner of the canvas; x increases to the right, and y increases down. To keep my layout organized, I use a standard blocks\r\n      size of 30 by 30, and offsets of 60.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">x = 30;\r\ny = 30;\r\nw = 30;\r\nh = 30;\r\noffset = 60;<\/pre><p>I like my ports with slightly different proportions, so I define them to be half the height of the other blocks. <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/add_block.html\"><tt>add_block<\/tt><\/a> specifies the source block and the destination path, which defines the block name. Block names must be unique for a given\r\n      system so <tt>add_block<\/tt> provides a <tt>MakeNameUnique<\/tt> option. (not used here)\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">pos = [x y+h\/4 x+w y+h*.75];\r\nadd_block(<span style=\"color: #A020F0\">'built-in\/Inport'<\/span>,[sys <span style=\"color: #A020F0\">'\/In1'<\/span>],<span style=\"color: #A020F0\">'Position'<\/span>,pos);<\/pre><p>I'll add an integrator block, offset to the right of the inport.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">pos = [(x+offset) y (x+offset)+w y+h];\r\nadd_block(<span style=\"color: #A020F0\">'built-in\/Integrator'<\/span>,[sys <span style=\"color: #A020F0\">'\/Int1'<\/span>],<span style=\"color: #A020F0\">'Position'<\/span>,pos)<\/pre><p>To connect the blocks, call add_line and provide the system name, source port and destination port.  The ports are designated\r\n      by the <tt>'blockname\/PortNum'<\/tt> format.  Default line routing is a direct line connection from the source to destination.  I prefer to use the <tt>autorouting<\/tt> option.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">add_line(sys,<span style=\"color: #A020F0\">'In1\/1'<\/span>,<span style=\"color: #A020F0\">'Int1\/1'<\/span>,<span style=\"color: #A020F0\">'autorouting'<\/span>,<span style=\"color: #A020F0\">'on'<\/span>)<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/seth\/2010Q1\/testmodel_1_mod.png\"> <\/p>\r\n   <p>When adding multiple blocks and lines, I group them into <tt>add_block\/add_line<\/tt> pairs to keep myself organized.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">pos = [(x+offset*2) y (x+offset*2)+w y+h];\r\nadd_block(<span style=\"color: #A020F0\">'built-in\/Integrator'<\/span>,[sys <span style=\"color: #A020F0\">'\/Int2'<\/span>],<span style=\"color: #A020F0\">'Position'<\/span>,pos)\r\nadd_line(sys,<span style=\"color: #A020F0\">'Int1\/1'<\/span>,<span style=\"color: #A020F0\">'Int2\/1'<\/span>,<span style=\"color: #A020F0\">'autorouting'<\/span>,<span style=\"color: #A020F0\">'on'<\/span>)\r\n\r\npos = [(x+offset*2) y+offset (x+offset*2)+w (y+offset)+h];\r\nadd_block(<span style=\"color: #A020F0\">'built-in\/Scope'<\/span>,[sys <span style=\"color: #A020F0\">'\/Scope1'<\/span>],<span style=\"color: #A020F0\">'Position'<\/span>,pos)\r\nadd_line(sys,<span style=\"color: #A020F0\">'Int1\/1'<\/span>,<span style=\"color: #A020F0\">'Scope1\/1'<\/span>,<span style=\"color: #A020F0\">'autorouting'<\/span>,<span style=\"color: #A020F0\">'on'<\/span>)<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/seth\/2010Q1\/testModel_4.png\"> <\/p>\r\n   <h3>Deleting Blocks and Lines<a name=\"10\"><\/a><\/h3>\r\n   <p>When deleting blocks, I call <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/delete_line.html\"><tt>delete_line<\/tt><\/a> before <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/delete_block.html\"><tt>delete_block<\/tt><\/a>. This is the reverse of what I did before. The commands are grouped in <tt>delete_line\/delete_block<\/tt> pairs.  For this example, I'll delete the integrator <tt>Int2<\/tt>, and add an outport.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">delete_line(sys,<span style=\"color: #A020F0\">'Int1\/1'<\/span>,<span style=\"color: #A020F0\">'Int2\/1'<\/span>)\r\ndelete_block([sys <span style=\"color: #A020F0\">'\/Int2'<\/span>])\r\n\r\npos = [(x+offset*2) y+h\/4 (x+offset*2)+w y+h*.75];\r\nadd_block(<span style=\"color: #A020F0\">'built-in\/Outport'<\/span>,[sys <span style=\"color: #A020F0\">'\/Out1'<\/span>],<span style=\"color: #A020F0\">'Position'<\/span>,pos)\r\nadd_line(sys,<span style=\"color: #A020F0\">'Int1\/1'<\/span>,<span style=\"color: #A020F0\">'Out1\/1'<\/span>)<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/seth\/2010Q1\/testmodel_5_mod.png\"> <\/p>\r\n   <h3>Replacing Blocks<a name=\"12\"><\/a><\/h3>\r\n   <p>Sometimes you don't really want to delete a block, you are just going to replace it. <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/replace_block.html\"><tt>replace_block<\/tt><\/a> gives you the capability to replace all blocks that match a specific criteria.  I reccommend carefully reading the documentation\r\n      to better understand this function.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">replace_block(sys,<span style=\"color: #A020F0\">'Name'<\/span>,<span style=\"color: #A020F0\">'In1'<\/span>,<span style=\"color: #A020F0\">'built-in\/Sin'<\/span>,<span style=\"color: #A020F0\">'noprompt'<\/span>);\r\nset_param([sys <span style=\"color: #A020F0\">'\/In1'<\/span>],<span style=\"color: #A020F0\">'Position'<\/span>,[x y x+w y+h],<span style=\"color: #A020F0\">'Name'<\/span>,<span style=\"color: #A020F0\">'Sine Wave'<\/span>);<\/pre><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/seth\/2010Q1\/testModel_6_mod.png\"> <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[t,x,y] = sim(sys);\r\nplot(t,y), ylim([-.5 2.5]), grid <span style=\"color: #A020F0\">on<\/span><\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/seth\/2010Q1\/modelConstruction_02.png\"> <h3>Now it's your turn<a name=\"14\"><\/a><\/h3>\r\n   <p>Do you use model construction commands? Why doesn't the cosine on that scope cross below zero?  Leave a <a href=\"https:\/\/blogs.mathworks.com\/seth\/?p=79&amp;#comment\">comment here<\/a> with your thoughts.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_5588ac0f2e114c8a8ac54519f160201d() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='5588ac0f2e114c8a8ac54519f160201d ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 5588ac0f2e114c8a8ac54519f160201d';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Seth Popinchalk';\r\n        copyright = 'Copyright 2010 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_5588ac0f2e114c8a8ac54519f160201d()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.9<br><\/p>\r\n<\/div>\r\n<!--\r\n5588ac0f2e114c8a8ac54519f160201d ##### SOURCE BEGIN #####\r\n%% Building models with MATLAB Code\r\n% Occasionally I get questions about how to build, modify, and add blocks,\r\n% to Simulink models using MATLAB commands.  In this post, I will to give a\r\n% basic overview of the common <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/bq3cxmi.html#bq3ftt5 model construction commands>.\r\n\r\n%% Start With a New System\r\n% Because you need to refer to the system so often when doing model\r\n% construction from M-code, I immediately save that off in a variable\r\n% called |sys|.  The\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/new_system.html |new_system|>\r\n% command created the empty model in memory, and you have to call\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/open_system.html |open_system|>\r\n% to display it on-screen.\r\nsys = 'testModel';\r\nnew_system(sys) % Create the model\r\nopen_system(sys) % Open the model\r\n\r\n%%\r\n% <<testModelEmpty.png>>\r\n\r\n%% Adding Blocks and Lines\r\n% When I add blocks to the canvas, I specify the position to provide proper\r\n% layout. The position parameter provides the top left (x,y) and lower\r\n% right (x+w,y+h) corners of the block.  The x and y values are relative to\r\n% the origin (0,0) in the upper left corner of the canvas; x increases to\r\n% the right, and y increases down. To keep my layout organized, I use a\r\n% standard blocks size of 30 by 30, and offsets of 60.\r\nx = 30;\r\ny = 30;\r\nw = 30;\r\nh = 30;\r\noffset = 60;\r\n%%\r\n% I like my ports with slightly different proportions, so I define them\r\n% to be half the height of the other blocks.\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/add_block.html |add_block|>\r\n% specifies the source block and the destination path, which defines the\r\n% block name. Block names must be unique for a given system so |add_block|\r\n% provides a |MakeNameUnique| option. (not used here)\r\npos = [x y+h\/4 x+w y+h*.75];\r\nadd_block('built-in\/Inport',[sys '\/In1'],'Position',pos);\r\n\r\n%%\r\n% I'll add an integrator block, offset to the right of the inport.\r\npos = [(x+offset) y (x+offset)+w y+h];\r\nadd_block('built-in\/Integrator',[sys '\/Int1'],'Position',pos)\r\n\r\n%%\r\n% To connect the blocks, call add_line and provide the system name, source\r\n% port and destination port.  The ports are designated by the \r\n% |'blockname\/PortNum'| format.  Default line routing is a direct line\r\n% connection from the source to destination.  I prefer to use the\r\n% |autorouting| option.\r\nadd_line(sys,'In1\/1','Int1\/1','autorouting','on')\r\n\r\n%%\r\n% <<testModel_1_mod.png>>\r\n\r\n%%\r\n% When adding multiple blocks and lines, I group them into\r\n% |add_block\/add_line| pairs to keep myself organized.\r\npos = [(x+offset*2) y (x+offset*2)+w y+h];\r\nadd_block('built-in\/Integrator',[sys '\/Int2'],'Position',pos)\r\nadd_line(sys,'Int1\/1','Int2\/1','autorouting','on')\r\n\r\npos = [(x+offset*2) y+offset (x+offset*2)+w (y+offset)+h];\r\nadd_block('built-in\/Scope',[sys '\/Scope1'],'Position',pos)\r\nadd_line(sys,'Int1\/1','Scope1\/1','autorouting','on')\r\n\r\n%%\r\n% <<testModel_4.png>>\r\n\r\n%% Deleting Blocks and Lines\r\n% When deleting blocks, I call <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/delete_line.html |delete_line|> \r\n% before <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/delete_block.html |delete_block|>. \r\n% This is the reverse of what I did before. The commands are grouped in\r\n% |delete_line\/delete_block| pairs.  For this example, I'll delete the\r\n% integrator |Int2|, and add an outport.\r\n\r\ndelete_line(sys,'Int1\/1','Int2\/1')\r\ndelete_block([sys '\/Int2'])\r\n\r\npos = [(x+offset*2) y+h\/4 (x+offset*2)+w y+h*.75];\r\nadd_block('built-in\/Outport',[sys '\/Out1'],'Position',pos)\r\nadd_line(sys,'Int1\/1','Out1\/1')\r\n\r\n%%\r\n% <<testModel_5_mod.png>>\r\n\r\n%% Replacing Blocks\r\n% Sometimes you don't really want to delete a block, you are just going to\r\n% replace it.\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009b\/toolbox\/simulink\/slref\/replace_block.html |replace_block|> \r\n% gives you the capability to replace all blocks that match a specific\r\n% criteria.  I reccommend carefully reading the documentation to better\r\n% understand this function.\r\nreplace_block(sys,'Name','In1','built-in\/Sin','noprompt');\r\nset_param([sys '\/In1'],'Position',[x y x+w y+h],'Name','Sine Wave');\r\n\r\n%%\r\n% <<testModel_6_mod.png>>\r\n\r\n[t,x,y] = sim(sys);\r\nplot(t,y), ylim([-.5 2.5]), grid on\r\n\r\n%% Now it's your turn\r\n% Do you use model construction commands? Why doesn't the cosine on that\r\n% scope cross below zero?  Leave a <https:\/\/blogs.mathworks.com\/seth\/?p=79&#comment comment here> with your\r\n% thoughts.\r\n\r\n##### SOURCE END ##### 5588ac0f2e114c8a8ac54519f160201d\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Occasionally I get questions about how to build, modify, and add blocks, to Simulink models using MATLAB commands.  In this\r\n         post, I will to give a basic overview of the common... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/simulink\/2010\/01\/21\/building-models-with-matlab-code\/\">read more >><\/a><\/p>","protected":false},"author":40,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[15,67],"tags":[118,441],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/posts\/79"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/users\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/comments?post=79"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/posts\/79\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/media?parent=79"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/categories?post=79"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/simulink\/wp-json\/wp\/v2\/tags?post=79"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}