{"id":11026,"date":"2019-09-27T13:00:29","date_gmt":"2019-09-27T17:00:29","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=11026"},"modified":"2019-10-02T11:34:53","modified_gmt":"2019-10-02T15:34:53","slug":"new-with-r2019b-function-argument-validation","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2019\/09\/27\/new-with-r2019b-function-argument-validation\/","title":{"rendered":"New with R2019b &#8211; Function Argument Validation"},"content":{"rendered":"\r\n\r\n<div class=\"content\"><p><a href=\"http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/869871\">Jiro<\/a>&#8216;s Pick this week is <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/function-argument-validation-1.html\">Function Argument Validation<\/a>, which is a new R2019b feature that I&#8217;m really excited about.<\/p><p>If you search for <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange?q=function+argument+validation\">&#8220;function argument validation&#8221;<\/a> or <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange?q=input+validation\">&#8220;input validation&#8221;<\/a> in File Exchange, you will see quite a few entries on it. Some are actual utilities for doing validation, while others are regular entries with validation functions within them. There are also argument parsing entries for parsing optional arguments.<\/p><p>Input validation can be a tedious task and may require thorough consideration of logic to ensure robust code. Let&#8217;s look at an example.<\/p><p>Let&#8217;s say that I want to create a function that takes an arbitrary number of data sets and creates an overlapping histogram. In addition, I&#8217;d like the function to take optional param-value pair inputs to customize some properties of the plot. So the input argument looks something like this:<\/p><pre>  myhistogram(DATA1, DATA2, ..., PARAM1, VALUE1, PARAM2, VALUE2, ...)<\/pre><p>You can imagine how tricky this may be to implement. Doable, but tedious. I would need to do some parsing to first see how many data sets are passed in. I may do that by checking from the first input to see if it is not a parameter name I&#8217;m looking for. After that, I repeatedly inspect the parameter-value pairs and assign the values to the appropriate parameters. Again, doable, but tedious.<\/p><p>With the new function argument validation, the parsing and the validation can be expressed in a compact, easy-to-understand way. Here is the whole code:<\/p><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/jiro\/potw_functionarguments\/potw_myhistogram.png\" alt=\"\"> <\/p><p>Let&#8217;s see how it works.<\/p><pre class=\"codeinput\">data1 = randn(2000,1);\r\ndata2 = 1 + randn(5000,1);\r\ndata3 = 3 + randn(4000,1);\r\nmyhistogram(data1,data2,data3)\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/jiro\/potw_functionarguments\/potw_functionarguments_01.png\" alt=\"\"> <p>I can call it with some parameters<\/p><pre class=\"codeinput\">myhistogram(data1,data2,data3,<span class=\"string\">'nbins'<\/span>,25,<span class=\"string\">'showlegend'<\/span>,true)\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/jiro\/potw_functionarguments\/potw_functionarguments_02.png\" alt=\"\"> <p>If I mistype my parameters, the validation functions catch the error.<\/p><pre class=\"codeinput\"><span class=\"keyword\">try<\/span>\r\n    myhistogram(data1,data2,data3,<span class=\"string\">'nbins'<\/span>,5.5,<span class=\"string\">'showlegend'<\/span>,true)\r\n<span class=\"keyword\">catch<\/span> ME\r\n    disp(ME.message)\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">Invalid name-value argument 'nbins'. Value must be integer.\r\n<\/pre><p><b>Comments<\/b><\/p><p>Give it a try and let us know what you think <a href=\"http:\/\/blogs.mathworks.com\/pick\/?p=11026#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_189fc97115f94bb0b23f796ec08f8089() {\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='189fc97115f94bb0b23f796ec08f8089 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 189fc97115f94bb0b23f796ec08f8089';\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        copyright = 'Copyright 2019 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 copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\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     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_189fc97115f94bb0b23f796ec08f8089()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2019b<br><\/p><p class=\"footer\"><br>\r\n      Published with MATLAB&reg; R2019b<br><\/p><\/div><!--\r\n189fc97115f94bb0b23f796ec08f8089 ##### SOURCE BEGIN #####\r\n%%\r\n% <http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/869871 Jiro>'s\r\n% Pick this week is\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/function-argument-validation-1.html\r\n% Function Argument Validation>, which is a new R2019b feature that I'm\r\n% really excited about.\r\n%\r\n% If you search for\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange?q=function+argument+validation\r\n% \"function argument validation\"> or\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange?q=input+validation\r\n% \"input validation\"> in File Exchange, you will see quite a few entries on\r\n% it. Some are actual utilities for doing validation, while others are\r\n% regular entries with validation functions within them. There are also\r\n% argument parsing entries for parsing optional arguments.\r\n%\r\n% Input validation can be a tedious task and may require thorough\r\n% consideration of logic to ensure robust code. Let's look at an example.\r\n%\r\n% Let's say that I want to create a function that takes an arbitrary number\r\n% of data sets and creates an overlapping histogram. In addition, I'd like\r\n% the function to take optional param-value pair inputs to customize\r\n% some properties of the plot. So the input argument looks something like\r\n% this:\r\n%\r\n%    myhistogram(DATA1, DATA2, ..., PARAM1, VALUE1, PARAM2, VALUE2, ...)\r\n%\r\n% You can imagine how tricky this may be to implement. Doable, but tedious.\r\n% I would need to do some parsing to first see how many data sets are\r\n% passed in. I may do that by checking from the first input to see if it is\r\n% not a parameter name I'm looking for. After that, I repeatedly inspect\r\n% the parameter-value pairs and assign the values to the appropriate\r\n% parameters. Again, doable, but tedious.\r\n%\r\n% With the new function argument validation, the parsing and the validation\r\n% can be expressed in a compact, easy-to-understand way. Here is the whole\r\n% code:\r\n%\r\n% <<potw_myhistogram.png>>\r\n%\r\n% Let's see how it works.\r\n\r\ndata1 = randn(2000,1);\r\ndata2 = 1 + randn(5000,1);\r\ndata3 = 3 + randn(4000,1);\r\nmyhistogram(data1,data2,data3)\r\n\r\n%%\r\n% I can call it with some parameters\r\n\r\nmyhistogram(data1,data2,data3,'nbins',25,'showlegend',true)\r\n\r\n%%\r\n% If I mistype my parameters, the validation functions catch the error.\r\n\r\ntry\r\n    myhistogram(data1,data2,data3,'nbins',5.5,'showlegend',true)\r\ncatch ME\r\n    disp(ME.message)\r\nend\r\n\r\n%% \r\n% *Comments*\r\n%\r\n% Give it a try and let us know what you think\r\n% <http:\/\/blogs.mathworks.com\/pick\/?p=11026#respond here>.\r\n\r\n##### SOURCE END ##### 189fc97115f94bb0b23f796ec08f8089\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/jiro\/potw_functionarguments\/potw_myhistogram.png\" onError=\"this.style.display ='none';\" \/><\/div><p>\r\n\r\nJiro&#8216;s Pick this week is Function Argument Validation, which is a new R2019b feature that I&#8217;m really excited about.If you search for &#8220;function argument validation&#8221; or&#8230; <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2019\/09\/27\/new-with-r2019b-function-argument-validation\/\">read more >><\/a><\/p>","protected":false},"author":35,"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\/11026"}],"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\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=11026"}],"version-history":[{"count":5,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/11026\/revisions"}],"predecessor-version":[{"id":11038,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/11026\/revisions\/11038"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=11026"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=11026"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=11026"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}