{"id":183,"date":"2009-05-05T13:18:10","date_gmt":"2009-05-05T13:18:10","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2009\/05\/05\/nice-way-to-set-function-defaults\/"},"modified":"2019-10-31T11:02:51","modified_gmt":"2019-10-31T16:02:51","slug":"nice-way-to-set-function-defaults","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2009\/05\/05\/nice-way-to-set-function-defaults\/","title":{"rendered":"Nice Way to Set Function Defaults"},"content":{"rendered":"\r\n\r\n<div class=\"content\"><!--introduction--><p>Last week, I wrote <a href=\"http:\/\/blogs.mathworks.com\/loren\/2009\/04\/28\/switching-things-up\/\">a post<\/a> on the <a href=\"http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/switch.html\"><tt>switch<\/tt><\/a> statement in MATLAB.  One theme in the comments was about using <tt>switch<\/tt> (or not!) for setting default values for input arguments that users didn't initialize.  I realized that there is a nice pattern for setting these values that uses some compact, but readable code.<\/p><p><b>There is new functionality in R2019B that supercedes these ideas.<\/b>  Please check out the new functionality for <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/arguments.html\">argument validation<\/a>.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#f9aedd9e-d6af-47ef-a932-3c0c5056add2\">Function Defaults<\/a><\/li><li><a href=\"#405d8db0-fe82-418c-91f0-1faa96906f24\">Setting Default Values<\/a><\/li><li><a href=\"#988fbf69-1c77-494e-933a-c304f94b8c7a\">Other Methods for Dealing with Optional Inputs<\/a><\/li><li><a href=\"#247f5726-3a6a-4467-85e1-4cfa1cea103e\">Your Techniques for Specifying Optional Values<\/a><\/li><\/ul><\/div><h4>Function Defaults<a name=\"f9aedd9e-d6af-47ef-a932-3c0c5056add2\"><\/a><\/h4><p>Sometimes I want to write a function that has some required inputs and some optional trailing arguments.  If the arguments are specified by their order, and not by parameter-value pairs, there is a nice way to accomplish this take advantage of <a href=\"http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/varargin.html\"><tt>varargin<\/tt><\/a>. Note that neither of these methods checks the validity of the overridden elements.<\/p><p>Suppose my function requires the first 2 inputs, but there are 3 others that the user can choose to set, or allow them to take default values. In this scenario, once they choose to set an optional input, they must set all the optional ones that precede it in the argument list.  Here's an example function header.<\/p><pre class=\"codeinput\">dbtype <span class=\"string\">somefun2<\/span> <span class=\"string\">1<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\n1     function y = somefun2(a,b,opt1,opt2,opt3)\r\n<\/pre><p>Here's another way I could write this function header, using <tt>varargin<\/tt>.<\/p><pre class=\"codeinput\">dbtype <span class=\"string\">somefun2Alt<\/span> <span class=\"string\">1<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\n1     function y = somefun2Alt(a,b,varargin)\r\n<\/pre><h4>Setting Default Values<a name=\"405d8db0-fe82-418c-91f0-1faa96906f24\"><\/a><\/h4><p>To <b>set<\/b> default values in <tt>somefun2<\/tt>, I could use a <tt>switch<\/tt> statement or use <tt>if-elseif<\/tt> constructs.  Here I chose to use a <tt>switch<\/tt> statement.<\/p><pre class=\"codeinput\">type <span class=\"string\">somefun2<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nfunction y = somefun2(a,b,opt1,opt2,opt3)\r\n% Some function with 2 required inputs, 3 optional.\r\n\r\n% Check number of inputs.\r\nif nargin &gt; 5\r\n    error('myfuns:somefun2:TooManyInputs', ...\r\n        'requires at most 3 optional inputs');\r\nend\r\n\r\n% Fill in unset optional values.\r\nswitch nargin\r\n    case 2\r\n        opt1 = eps;\r\n        opt2 = 17;\r\n        opt3 = @magic;\r\n    case 3\r\n        opt2 = 17;\r\n        opt3 = @magic;\r\n    case 4\r\n        opt3 = @magic;\r\nend\r\n<\/pre><p>The code is verbose and, in my opinion, not very pretty.  It's also error-prone.  If I decide to change a default setting for one value, I have to update each relevant <tt>case<\/tt>.  What a drag!<\/p><p>Here's a way to set the defaults in one location and then overwrite the ones the user specified.<\/p><pre class=\"codeinput\">type <span class=\"string\">somefun2Alt<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nfunction y = somefun2Alt(a,b,varargin)\r\n% Some function that requires 2 inputs and has some optional inputs.\r\n\r\n% only want 3 optional inputs at most\r\nnumvarargs = length(varargin);\r\nif numvarargs &gt; 3\r\n    error('myfuns:somefun2Alt:TooManyInputs', ...\r\n        'requires at most 3 optional inputs');\r\nend\r\n\r\n% set defaults for optional inputs\r\noptargs = {eps 17 @magic};\r\n\r\n% now put these defaults into the valuesToUse cell array, \r\n% and overwrite the ones specified in varargin.\r\noptargs(1:numvarargs) = varargin;\r\n% or ...\r\n% [optargs{1:numvarargs}] = varargin{:};\r\n\r\n% Place optional args in memorable variable names\r\n[tol, mynum, func] = optargs{:};\r\n<\/pre><p>First I place the default optional values into a cell array <tt>optargs<\/tt>.  I then copy the cells from <tt>varargin<\/tt> to the correct cells in <tt>optargs<\/tt> and I have overridden the defaults.  I have only one place where the default values are set, and the code doesn't grow dramatically in length as I add additional optional inputs.  Finally, I spread out the cells from <tt>varargin<\/tt> into well-named individual variables, if I want to.  Since each element in a cell array is its own MATLAB array, and MATLAB has copy-on-write behavior, I am not creating extra copies of these optional inputs (see <a href=\"http:\/\/blogs.mathworks.com\/loren\/2006\/05\/10\/memory-management-for-functions-and-variables\/\">this post<\/a> for more information).<\/p><h4>Other Methods for Dealing with Optional Inputs<a name=\"988fbf69-1c77-494e-933a-c304f94b8c7a\"><\/a><\/h4><p>There are other methods for dealing with optional inputs.  These include specifying parameter-value pairs.  With or without such pairs, you can use <a href=\"http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/inputparser.html\"><tt>inputParser<\/tt><\/a> to help set the values you use.  You can specify the optional input in a <a href=\"http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/struct.html\"><tt>struct<\/tt><\/a>, with fields containing the various options, and you can use cell arrays, but then you have to decide how to structure and specify the contents.<\/p><h4>Your Techniques for Specifying Optional Values<a name=\"247f5726-3a6a-4467-85e1-4cfa1cea103e\"><\/a><\/h4><p>Do you have a technique for specifying optional values that works well for you?  Please share with us <a href=\"http:\/\/blogs.mathworks.com\/loren\/?p=183#respond\">here<\/a>.<\/p><p><i>Loren Shure<\/i> <i>Copyright 2009 The MathWorks, Inc.<\/i><\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_4c3ce01afc4b4a6fa4b4e1035701b737() {\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='4c3ce01afc4b4a6fa4b4e1035701b737 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 4c3ce01afc4b4a6fa4b4e1035701b737';\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_4c3ce01afc4b4a6fa4b4e1035701b737()\"><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><\/div><!--\r\n4c3ce01afc4b4a6fa4b4e1035701b737 ##### SOURCE BEGIN #####\r\n%% Nice Way to Set Function Defaults\r\n% Last week, I wrote <http:\/\/blogs.mathworks.com\/loren\/2009\/04\/28\/switching-things-up\/ a post>\r\n% on the\r\n% <http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/switch.html |switch|>\r\n% statement in MATLAB.  One theme in the comments was about using |switch|\r\n% (or not!) for setting default values for input arguments that users\r\n% didn't initialize.  I realized that there is a nice pattern for setting\r\n% these values that uses some compact, but readable code.\r\n%\r\n% *There is new functionality in R2019B that supercedes these ideas.*  Please\r\n% check out the new functionality for\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/arguments.html argument\r\n% validation>.\r\n%% Function Defaults\r\n% Sometimes I want to write a function that has some required inputs and\r\n% some optional trailing arguments.  If the arguments are specified by\r\n% their order, and not by parameter-value pairs, there is a nice way to\r\n% accomplish this take advantage of \r\n% <http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/varargin.html |varargin|>.\r\n% Note that neither of these methods checks the validity of the overridden\r\n% elements.\r\n%%\r\n% Suppose my function requires the first 2 inputs, but there are 3 others\r\n% that the user can choose to set, or allow them to take default values.\r\n% In this scenario, once they choose to set an optional input, they must\r\n% set all the optional ones that precede it in the argument list.  Here's\r\n% an example function header.\r\ndbtype somefun2 1\r\n%%\r\n% Here's another way I could write this function header, using |varargin|.\r\ndbtype somefun2Alt 1\r\n%% Setting Default Values\r\n% To *set* default values in |somefun2|, I could use a |switch| statement or\r\n% use |if-elseif| constructs.  Here I chose to use a |switch| statement.\r\ntype somefun2\r\n%%\r\n% The code is verbose and, in my opinion, not very pretty.  It's also\r\n% error-prone.  If I decide to change a default setting for one value, I\r\n% have to update each relevant |case|.  What a drag!\r\n%%\r\n% Here's a way to set the defaults in one location and then overwrite the\r\n% ones the user specified.\r\ntype somefun2Alt\r\n%%\r\n% First I place the default optional values into a cell array |optargs|.  I\r\n% then copy the cells from |varargin| to the correct cells in |optargs| and\r\n% I have overridden the defaults.  I have only one place where the default\r\n% values are set, and the code doesn't grow dramatically in length as I add\r\n% additional optional inputs.  Finally, I spread out the cells from\r\n% |varargin| into well-named individual variables, if I want to.  Since\r\n% each element in a cell array is its own MATLAB array, and MATLAB has\r\n% copy-on-write behavior, I am not creating extra copies of these optional\r\n% inputs (see <http:\/\/blogs.mathworks.com\/loren\/2006\/05\/10\/memory-management-for-functions-and-variables\/ this post>\r\n% for more information).\r\n%% Other Methods for Dealing with Optional Inputs\r\n% There are other methods for dealing with optional inputs.  These include\r\n% specifying parameter-value pairs.  With or without such pairs, you can\r\n% use <http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/inputparser.html |inputParser|>\r\n% to help set the values you use.  You can specify the optional input in a\r\n% <http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/struct.html |struct|>, \r\n% with fields containing the various options, and you can use cell arrays,\r\n% but then you have to decide how to structure and specify the contents. \r\n%% Your Techniques for Specifying Optional Values\r\n% Do you have a technique for specifying optional values that works well\r\n% for you?  Please share with us\r\n% <http:\/\/blogs.mathworks.com\/loren\/?p=183#respond here>.\r\n\r\n%%\r\n% _Loren Shure_\r\n% _Copyright 2009 The MathWorks, Inc._\r\n\r\n##### SOURCE END ##### 4c3ce01afc4b4a6fa4b4e1035701b737\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>Last week, I wrote <a href=\"http:\/\/blogs.mathworks.com\/loren\/2009\/04\/28\/switching-things-up\/\">a post<\/a> on the <a href=\"http:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/ref\/switch.html\"><tt>switch<\/tt><\/a> statement in MATLAB.  One theme in the comments was about using <tt>switch<\/tt> (or not!) for setting default values for input arguments that users didn't initialize.  I realized that there is a nice pattern for setting these values that uses some compact, but readable code.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2009\/05\/05\/nice-way-to-set-function-defaults\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,17,30],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/183"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=183"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/183\/revisions"}],"predecessor-version":[{"id":3497,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/183\/revisions\/3497"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=183"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=183"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=183"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}