{"id":2638,"date":"2011-01-14T14:14:15","date_gmt":"2011-01-14T14:14:15","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/2011\/01\/14\/good-matlab-coding-practices\/"},"modified":"2016-11-16T15:12:42","modified_gmt":"2016-11-16T20:12:42","slug":"good-matlab-coding-practices","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2011\/01\/14\/good-matlab-coding-practices\/","title":{"rendered":"Good MATLAB Coding Practices"},"content":{"rendered":"<div class=\"content\">\n<p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/911\">Brett<\/a>&#8216;s Pick this week has three parts, and is really a tip of the hat to three authors who have taken the initiative to try to<br \/>\npromote and teach good MATLAB programming practices. In particular, I&#8217;d like to acknowledge <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/1736\">Michael Robbins<\/a> for <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/2371-good-matlab-programming-practices\">&#8220;Good MATLAB Programming Practices&#8221;<\/a>; <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/14582\">Pascal Getreuer<\/a> for <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/5685-writing-fast-matlab-code\">&#8220;Writing Fast MATLAB Code&#8221;<\/a>; and <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/34666\">Nico Schl\u00f6mer<\/a> for <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/22943-guidelines-for-writing-clean-and-fast-code-in-matlab\">&#8220;Guidelines for writing clean and fast code in MATLAB.&#8221;<\/a><\/p>\n<p>I recall fondly my first attempts at writing a bit of MATLAB code; I believe the year was 1996. I fumbled around, read a few<br \/>\n<a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/learn_matlab\/bqr_2pl.html\">&#8220;Getting Started&#8221;<\/a> documents, and began writing code. I was amazed at how easily I could get MATLAB to do what I wanted it to do! MATLAB is<br \/>\na fourth-generation interpreted language, and it&#8217;s relatively forgiving; somehow even ugly code manages to work. Over the<br \/>\nyears, as I grew more confident (and competent) with the language, I learned just how poor my coding practices were. And in<br \/>\nsome cases, the difference between good code and bad code can be orders of magnitude difference in performance (as measured<br \/>\nby computation time). It behooves the user to spend some time building a greater mastery of the language; dividends will come<br \/>\nnot only in improved readability and maintainability, but in improved performance as well. Moments before writing this post,<br \/>\nI had the very unpleasant experience of looking back at my 15-year-old code; it could appear in a textbook of poor coding<br \/>\npractices!<\/p>\n<p>Fortunately, Michael provided two versions of his &#8220;Good Programming Practices&#8221; (2003); I had a font problem with one, but<br \/>\nwas able to read the second without difficulty. Michael&#8217;s document provides a solid page of useful gems. Among them, he advises<br \/>\nthat: &#8220;creative use of FIND, PROD, SUM, CUMSUM, NaN, REPMAT, RESHAPE, ONES and ZEROS can really help vectorize your code,<br \/>\nbut try not to make the code too cryptic. There is a tradeoff between execution time and readability. If your statement is<br \/>\ncryptic, either include an equivalent (but slow and easy to read) version in a comment or write a MEX file.&#8221; He also suggests<br \/>\nthat the user &#8220;use PROFILE to identify where you need to work on speed improvements.&#8221;<\/p>\n<p>Pascal&#8217;s &#8220;Writing Fast MATLAB Code&#8221; (2009) is more ambitious. In a beautifully formatted document, he lays out 12 chapters<br \/>\non the topic of better utilization of the MATLAB language:<\/p>\n<div>\n<ul>\n<li>Introduction<\/li>\n<li>The Profiler<\/li>\n<li>Array Preallocation<\/li>\n<li>JIT Acceleration<\/li>\n<li>Vectorization<\/li>\n<li>Inlining Simple Functions<\/li>\n<li>Referencing Operations<\/li>\n<li>Solving Ax = b<\/li>\n<li>Numerical Integration<\/li>\n<li>Signal Processing<\/li>\n<li>Miscellaneous<\/li>\n<li>Further Reading<\/li>\n<\/ul>\n<\/div>\n<p>Nico cites Pascal&#8217;s file as an inspiration for his 2009 &#8220;Guidelines.&#8221; In 34 pages, he spouts some great suggestions &#8220;aimed<br \/>\nat MATLAB beginners who already know the syntax but feel are not yet quite experienced with it. Its goal is to give a number<br \/>\nof hints which enable the reader to write quality MATLAB programs and to avoid commonly made mistakes.&#8221;<\/p>\n<p>All of these files are worthy of a download and careful study. I wish I had had them back when I was getting started. It&#8217;s<br \/>\neasier to learn good habits than to break bad ones!<\/p>\n<p>By the way, we now have a video version of &#8220;Getting Started&#8221; with MATLAB, as well as several additional MathWorks&#8217; resources to guide the user to better coding practices.<br \/>\nOne I particularly recommend is the recorded webinar entitled &#8220;Speeding Up MATLAB Applications.&#8221; I also recommend that the motivated reader spend a bit of time following the links in <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_prog\/f8-705906.html\">this doc page on code performance<\/a>. You&#8217;ll quickly learn how to time and profile your code, plus lots of techniques for improving performance.<\/p>\n<p><a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=2638#respond\">Comments?<\/a><\/p>\n<p><script>\/\/ <![CDATA[\nfunction grabCode_e851edc0f6fb48d19095f1011958c7d4() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='e851edc0f6fb48d19095f1011958c7d4 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' e851edc0f6fb48d19095f1011958c7d4';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        author = 'Brett Shoelson';\n        copyright = 'Copyright 2011 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('\n\n\n\n<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\n\n\n\n\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }\n\/\/ ]]><\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight: lighter; font-style: italic; color: gray;\">\n<a><span style=\"font-size: x-small; font-style: italic;\">Get<br \/>\nthe MATLAB code<br \/>\n<noscript>(requires JavaScript)<\/noscript><\/span><\/a><\/p>\n<p>Published with MATLAB\u00ae 7.11<\/p>\n<\/div>\n<p><!--\ne851edc0f6fb48d19095f1011958c7d4 ##### SOURCE BEGIN #####\n%% Good MATLAB Coding Practices\n%%\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/911 Brett>'s\n% Pick this week has three parts, and is really a tip of the hat to three\n% authors who have taken the initiative to try to promote and teach good\n% MATLAB programming practices. In particular, I'd like to acknowledge\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/1736 Michael Robbins>\n% for\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/2371-good-matlab-programming-practices \"Good MATLAB Programming Practices\">;\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/14582 Pascal Getreuer>\n% for <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/5685-writing-fast-matlab-code \"Writing Fast MATLAB Code\">; and\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/34666 Nico Schl\u00c3\u00b6mer>\n% for <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/22943-guidelines-for-writing-clean-and-fast-code-in-matlab \"Guidelines for writing clean and fast code in MATLAB.\">\n\n%%\n% I recall fondly my first attempts at writing a bit of MATLAB code; I\n% believe the year was 1996. I fumbled around, read a few\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/learn_matlab\/bqr_2pl.html \"Getting Started\">\n% documents, and began writing code. I was amazed at how easily I could\n% get MATLAB to do what I wanted it to do! MATLAB is a fourth-generation interpreted language, and it's relatively forgiving; somehow even ugly code manages to work.\n% Over the years, as I grew more confident (and competent) with the language, I learned just how poor my coding practices were. And in some cases, the difference between good code and bad code can be orders of magnitude difference in performance (as measured by computation time).\n% It behooves the user to spend some time building a greater mastery of the language; dividends will come not only in improved readability and maintainability, but in improved performance as well.\n% Moments before writing this post, I had the very unpleasant experience of looking back at my 15-year-old code; it could appear in a\n% textbook of poor coding practices!\n\n%%\n% Fortunately, Michael provided two versions of his \"Good Programming Practices\" (2003);\n% I had a font problem with one, but was able to read the second without difficulty.\n% Michael's document provides a solid page of useful gems. Among them, he advises that:\n% \"creative use of FIND, PROD, SUM, CUMSUM, NaN, REPMAT, RESHAPE, ONES and ZEROS can really help vectorize your code, but try not to make the code too cryptic. There is a tradeoff between execution time and readability. If your statement is cryptic, either include\n% an equivalent (but slow and easy to read) version in a comment or write a\n% MEX file.\" He also suggests that the user \"use PROFILE to identify where you need\n% to work on speed improvements.\"\n\n%%\n% Pascal's \"Writing Fast MATLAB Code\" (2009) is more ambitious. In a beautifully\n% formatted document, he lays out 12 chapters on the topic of better\n% utilization of the MATLAB language:\n%\n% * Introduction\n% * The Profiler\n% * Array Preallocation\n% * JIT Acceleration\n% * Vectorization\n% * Inlining Simple Functions\n% * Referencing Operations\n% * Solving Ax = b\n% * Numerical Integration\n% * Signal Processing\n% * Miscellaneous\n% * Further Reading\n%\n%%\n% Nico cites Pascal's file as an inspiration for his 2009 \"Guidelines.\" In\n% 34 pages, he spouts some great suggestions \"aimed at MATLAB beginners who already know the\n% syntax but feel are not yet quite experienced with it. Its goal is to give a\n% number of hints which enable the reader to write quality MATLAB programs\n% and to avoid commonly made mistakes.\"\n%\n%%\n% All of these files are worthy of a download and careful study. I wish I\n% had had them back when I was getting started. It's easier to learn good\n% habits than to break bad ones!\n%\n%%\n% By the way, we now have a <https:\/\/www.mathworks.com\/videos\/matlab\/getting-started-with-matlab.html?s_cid=HP_MI_product_mlgetstarted video version>\n% of \"Getting Started\" with MATLAB,as well as several additional MathWorks' resources to guide the\n% user to better coding practices. One I particularly recommend is the\n% recorded webinar entitled <https:\/\/www.mathworks.com\/company\/events\/webinars\/wbnr49643.html?id=49643&p1=772994042&p2=772994060 \"Speeding Up MATLAB Applications.\">\n% I also recommend that the motivated reader spend a bit of time following\n% the links in <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_prog\/f8-705906.html this doc page on code performance>. You'll quickly learn how to time and profile your code,\n% plus lots of techniques for improving performance.\n\n%%\n% <https:\/\/blogs.mathworks.com\/pick\/?p=2638#respond Comments?>\n\n##### SOURCE END ##### e851edc0f6fb48d19095f1011958c7d4\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\nBrett&#8216;s Pick this week has three parts, and is really a tip of the hat to three authors who have taken the initiative to try to<br \/>\npromote and teach good MATLAB programming practices. In&#8230; <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2011\/01\/14\/good-matlab-coding-practices\/\">read more >><\/a><\/p>\n","protected":false},"author":34,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/2638"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/34"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=2638"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/2638\/revisions"}],"predecessor-version":[{"id":8047,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/2638\/revisions\/8047"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=2638"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=2638"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=2638"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}