{"id":251,"date":"2010-10-21T12:33:12","date_gmt":"2010-10-21T12:33:12","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2010\/10\/21\/delaying-evaluation-of-function-inputs\/"},"modified":"2017-06-07T21:15:41","modified_gmt":"2017-06-08T02:15:41","slug":"delaying-evaluation-of-function-inputs","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2010\/10\/21\/delaying-evaluation-of-function-inputs\/","title":{"rendered":"Delaying Evaluation of Function Inputs"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>When you call a function in MATLAB, MATLAB first evaluates all the inputs, and then passes these (possibly) computed values\r\n         as the inputs. Recently Ljubomir Josifovski asked if there was a way to <a href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/02\/08\/use-nested-functions-to-memoize-costly-functions\/#comment-31749\">delay evaluation of function inputs<\/a> and only evaluate them on demand. Here's what I came up with.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Use Anonymous Functions<\/a><\/li>\r\n         <li><a href=\"#2\">Experiment<\/a><\/li>\r\n         <li><a href=\"#4\">Quick Comparison<\/a><\/li>\r\n         <li><a href=\"#7\">How To Take Advantage<\/a><\/li>\r\n         <li><a href=\"#8\">What's Your Strategy?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Use Anonymous Functions<a name=\"1\"><\/a><\/h3>\r\n   <p>Instead of calling the function with expressions as input values, create those expressions as <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_prog\/f4-70115.html\">anonymous functions<\/a> with no inputs.\r\n   <\/p>\r\n   <h3>Experiment<a name=\"2\"><\/a><\/h3>\r\n   <p>Let's create an array and an expression to evaluate.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">a = rand(2000);\r\ntic, f = @() a'*a, toc<\/pre><pre style=\"font-style:oblique\">f = \r\n    @()a'*a\r\nElapsed time is 0.003365 seconds.\r\n<\/pre><p>You can see that setting up the anonymous function <tt>f<\/tt> doesn't take a lot of time.\r\n   <\/p>\r\n   <h3>Quick Comparison<a name=\"4\"><\/a><\/h3>\r\n   <p>We aren't passing arguments here, but comparing the direct computation time for <tt>a'*a<\/tt> with evaluating the same quantity via the anonymous function.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">tic, b = a'*a; toc\r\ntic, c = f(); toc<\/pre><pre style=\"font-style:oblique\">Elapsed time is 0.508455 seconds.\r\nElapsed time is 0.482722 seconds.\r\n<\/pre><p>Setting up the function handle takes little time, but the evaluation is similar to the time for the expression itself.<\/p>\r\n   <p>This is what <tt>timeit<\/tt>, Steve Eddins' utility for benchmark timing, uses just this approach.  <tt>timeit<\/tt> helps wash out first time evaluation costs and other timing artifacts that can show up in benchmarking.  So let's try using\r\n      that now for the anonymous function evaluation.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">timeit(f)<\/pre><pre style=\"font-style:oblique\">ans =\r\n         0.456538375738468\r\n<\/pre><h3>How To Take Advantage<a name=\"7\"><\/a><\/h3>\r\n   <p>Now, if you want your function to evaluate either expression 1 or expression 2 based on something criterion, you can do so\r\n      by passing in the two expressions as anonymous functions and using some logic like this.\r\n   <\/p><pre>      if criterion == true\r\n         y = expr1();\r\n      else\r\n         y = expr2();\r\n      end<\/pre><h3>What's Your Strategy?<a name=\"8\"><\/a><\/h3>\r\n   <p>If you want to streamline your computations, do you have a strategy for delaying evaluation of expressions until necessary?\r\n       How do you do this? Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=251#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_160ced1e1b564f478983b2a9e10f0d25() {\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='160ced1e1b564f478983b2a9e10f0d25 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 160ced1e1b564f478983b2a9e10f0d25';\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 = 'Loren Shure';\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_160ced1e1b564f478983b2a9e10f0d25()\"><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.11<br><\/p>\r\n<\/div>\r\n<!--\r\n160ced1e1b564f478983b2a9e10f0d25 ##### SOURCE BEGIN #####\r\n%% Delaying Evaluation of Function Inputs\r\n% When you call a function in MATLAB, MATLAB first evaluates all the\r\n% inputs, and then passes these (possibly) computed values as the inputs.\r\n% Recently Ljubomir Josifovski asked if there was a way to \r\n% <https:\/\/blogs.mathworks.com\/loren\/2006\/02\/08\/use-nested-functions-to-memoize-costly-functions\/#comment-31749\r\n% delay evaluation of function inputs> and only evaluate them on demand.\r\n% Here's what I came up with.\r\n%% Use Anonymous Functions\r\n% Instead of calling the function with expressions as input values, create\r\n% those expressions as\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/matlab_prog\/f4-70115.html\r\n% anonymous functions> with no inputs.\r\n%% Experiment\r\n% Let's create an array and an expression to evaluate.\r\na = rand(2000);\r\ntic, f = @() a'*a, toc \r\n\r\n%% \r\n% You can see that setting up the anonymous function |f| doesn't take a lot\r\n% of time.\r\n%% Quick Comparison\r\n% We aren't passing arguments here, but comparing the direct computation\r\n% time for |a'*a| with evaluating the same quantity via the anonymous\r\n% function.\r\ntic, b = a'*a; toc \r\ntic, c = f(); toc\r\n%%\r\n% Setting up the function handle takes little time, but the evaluation is\r\n% similar to the time for the expression itself.\r\n%%\r\n% This is what <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/18798\r\n% |timeit|>, Steve Eddins' utility for benchmark timing, uses just this\r\n% approach.  |timeit| helps wash out first time evaluation costs and other\r\n% timing artifacts that can show up in benchmarking.  So let's try using\r\n% that now for the anonymous function evaluation.\r\ntimeit(f)\r\n%% How To Take Advantage\r\n% Now, if you want your function to evaluate either expression 1 or\r\n% expression 2 based on something criterion, you can do so by passing in\r\n% the two expressions as anonymous functions and using some logic like\r\n% this.\r\n%\r\n%        if criterion == true\r\n%           y = expr1();\r\n%        else\r\n%           y = expr2();\r\n%        end\r\n%% What's Your Strategy?\r\n% If you want to streamline your computations, do you have a strategy for\r\n% delaying evaluation of expressions until necessary?  How do you do this?\r\n% Let me know <https:\/\/blogs.mathworks.com\/loren\/?p=251#respond here>.\r\n##### SOURCE END ##### 160ced1e1b564f478983b2a9e10f0d25\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      When you call a function in MATLAB, MATLAB first evaluates all the inputs, and then passes these (possibly) computed values\r\n         as the inputs. Recently Ljubomir Josifovski asked if... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2010\/10\/21\/delaying-evaluation-of-function-inputs\/\">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,3,15],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/251"}],"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=251"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/251\/revisions"}],"predecessor-version":[{"id":2362,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/251\/revisions\/2362"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=251"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=251"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=251"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}