{"id":47,"date":"2006-07-26T09:00:41","date_gmt":"2006-07-26T14:00:41","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=47"},"modified":"2007-03-08T10:00:43","modified_gmt":"2007-03-08T15:00:43","slug":"trying-to-match-behavior-of-a-new-function-to-an-existing-one","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2006\/07\/26\/trying-to-match-behavior-of-a-new-function-to-an-existing-one\/","title":{"rendered":"Trying to Match Behavior of a New Function to an Existing One"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>We might want to a write a function that mimics the behavior of another related function, specifically with respect to input\r\n         shapes, etc. Ideally, we'd like to write it so we don't need to update our function if the related function changes how it\r\n         works, again with respect to input shapes and sizes, for example.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Error Checking<\/a><\/li>\r\n         <li><a href=\"#2\">Model our Function after the Arithmetic Operators<\/a><\/li>\r\n         <li><a href=\"#3\">The Function<\/a><\/li>\r\n         <li><a href=\"#5\">Here's the code.<\/a><\/li>\r\n         <li><a href=\"#7\">Alternate Program<\/a><\/li>\r\n         <li><a href=\"#8\">Comments<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Error Checking<a name=\"1\"><\/a><\/h3>\r\n   <p>In a perfect world, we'd do enough error checking so users get a reasonable error message when appropriate.  If the error\r\n      conditions change for the original function we're mimicking, we would normally need to change our function as well to match\r\n      the new behavior.\r\n   <\/p>\r\n   <h3>Model our Function after the Arithmetic Operators<a name=\"2\"><\/a><\/h3>\r\n   <p>Suppose we want a function to behave like the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/arithmetic-operators.html\">arithmetic operators<\/a> in MATLAB.  Here's the relevant rule for <tt>plus<\/tt>, and it applies to all the elementwise operators and most of the elementwise functions in MATLAB:\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li><tt>+<\/tt> Addition or unary plus. <tt>A+B<\/tt> adds <tt>A<\/tt> and <tt>B<\/tt>. <tt>A<\/tt> and <tt>B<\/tt> must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>The Function<a name=\"3\"><\/a><\/h3>\r\n   <p>We'd like to compute<\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/47\/tryMatch_eq100467.png\"> <\/p>\r\n   <p>Often, when I am creating a new M-file, I often include the error checking at the top of the file.  In the function I describe\r\n      here, I have made an effort to generalize the error checking so it could be reused, not my usual starting point!\r\n   <\/p>\r\n   <h3>Here's the code.<a name=\"5\"><\/a><\/h3><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">expMuSigChk<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     function y = expMuSigChk(x,mu,sigma)\r\n2     % Exponential function with parameters mu and sigma.\r\n3     \r\n4     % Check sizes.\r\n5     if chkSz(x,mu,sigma) == 0\r\n6         error('LSBlog:sizeMismatch','Non-scalar arguments must follow MATLAB dimension matching rules.');\r\n7     end\r\n8     % Since chkSz passed, we can now do our computations.\r\n9     y = exp(-0.5 * ((x - mu).\/sigma).^2) .\/ (sqrt(2*pi) .* sigma);\r\n10    \r\n11    function tf = chkSz(varargin)\r\n12    % Collect info on nonscalarsizes and return false if they aren't all the\r\n13    % same.\r\n14    nonscalarsizes = {};\r\n15    % convert sizes to strings so we can use unique on them\r\n16    for k = 1:length(varargin)\r\n17        if isscalar(varargin{k})\r\n18            continue\r\n19        end\r\n20        nonscalarsizes{end+1} = int2str(size(varargin{k})); \r\n21    end\r\n22    if isempty(nonscalarsizes)\r\n23        tf = true;\r\n24    else\r\n25        if length(unique(nonscalarsizes)) &gt; 1\r\n26            tf = false;\r\n27        else\r\n28            tf = true;\r\n29        end\r\n30    end\r\n31    \r\n\r\n<\/pre><p>Notice that there are about 20 lines (including comments) for the error checking AND if MATLAB rules were to ever change,\r\n      this check function here would have to change as well.   It would be far too easy to forget about this and then be surprised\r\n      when the behavior of <tt>expMuSigChk<\/tt> was no longer like MATLAB.\r\n   <\/p>\r\n   <h3>Alternate Program<a name=\"7\"><\/a><\/h3>\r\n   <p>Instead we can write a program that takes advantage of MATLAB effectively doing the error checking for us.  We <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html\"><tt>try<\/tt><\/a> to do the calculation, and if it fails, we issue and error.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">expMuSig<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     function y = expMuSig(x,mu,sigma)\r\n2     %Exponential function with parameters mu and sigma.\r\n3     try \r\n4         y = exp(-0.5 * ((x - mu).\/sigma).^2) .\/ (sqrt(2*pi) .* sigma);\r\n5     catch\r\n6         error('LSBlog:sizeMismatch','Non-scalar arguments must follow MATLAB dimension matching rules.');\r\n7     end\r\n<\/pre><h3>Comments<a name=\"8\"><\/a><\/h3>\r\n   <p>I plan to write on the topic of <tt>try<\/tt>, error checking, and using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/lasterror.html\"><tt>lasterror<\/tt><\/a> in the future, for those of you who are wondering about possibly polluting the error state of MATLAB.\r\n   <\/p>\r\n   <p>What are <a href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/07\/26\/trying-to-match-behavior-of-a-new-function-to-an-existing-one\/#respond\">your thoughts<\/a> on taking advantage of MATLAB in the way I describe here?\r\n   <\/p>\r\n   <p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br>\r\n      Published with MATLAB&reg; 7.2<br><\/p>\r\n<\/div>\r\n<!--\r\n##### SOURCE BEGIN #####\r\n%% Trying to Match Behavior of a New Function to an Existing One\r\n% We might want to a write a function that mimics the behavior of\r\n% another related function, specifically with respect to input shapes, etc.\r\n% Ideally, we'd like to write it so we don't need to update our function if\r\n% the related function changes how it works, again with respect to input\r\n% shapes and sizes, for example.\r\n%% Error Checking\r\n% In a perfect world, we'd do enough error checking so users get a\r\n% reasonable error message when appropriate.  If the error conditions\r\n% change for the original function we're mimicking, we would normally need\r\n% to change our function as well to match the new behavior.\r\n%% Model our Function after the Arithmetic Operators\r\n% Suppose we want a function to behave like the \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/arithmetic-operators.html arithmetic operators>\r\n% in MATLAB.  Here's the relevant rule for |plus|, and it applies to all\r\n% the elementwise operators and most of the elementwise functions in\r\n% MATLAB:\r\n%\r\n% * |+| Addition or unary plus. |A+B| adds |A| and |B|. |A| and |B| must\r\n% have the same size, unless one is a scalar. A scalar can be added to a\r\n% matrix of any size.\r\n%\r\n%% The Function\r\n% We'd like to compute\r\n% \r\n% $$e^{-0.5 * {((x-\\mu)\/\\sigma)}^2} \/ (\\surd (2 * \\pi) * \\sigma) $$\r\n% \r\n%%\r\n% Often, when I am creating a new M-file, I often include the error\r\n% checking at the top of the file.  In the function I describe here, I have\r\n% made an effort to generalize the error checking so it could be reused,\r\n% not my usual starting point! \r\n%% Here's the code.\r\ndbtype expMuSigChk\r\n%%\r\n% Notice that there are about 20 lines (including comments) for the error\r\n% checking AND if MATLAB rules were to ever change, this check function\r\n% here would have to change as well.   It would be far to easy to forget\r\n% about this and then be surprised when the behavior of |expMuSigChk| was\r\n% no longer like MATLAB.\r\n%% Alternate Program\r\n% Instead we can write a program that takes advantage of MATLAB effectively\r\n% doing the error checking for us.  We \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/try.html |try|>\r\n% to do the calculation, and if it fails, we issue and error.\r\ndbtype expMuSig\r\n%% Comments\r\n% I plan to write on the topic of |try|, error checking, and using\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/lasterror.html |lasterror|>\r\n% in the future, for those of you who are wondering about possibly\r\n% polluting the error state of MATLAB.  \r\n%%\r\n% What are <?p=47#your thoughts> on taking advantage of MATLAB in the way I\r\n% describe here?\r\n##### SOURCE END #####\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      We might want to a write a function that mimics the behavior of another related function, specifically with respect to input\r\n         shapes, etc. Ideally, we'd like to write it so we... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/07\/26\/trying-to-match-behavior-of-a-new-function-to-an-existing-one\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[10,15,11],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/47"}],"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=47"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/47\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=47"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=47"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=47"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}