{"id":175,"date":"2009-03-13T14:47:33","date_gmt":"2009-03-13T14:47:33","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2009\/03\/13\/using-str2func-for-anonymous-function-handle-creation\/"},"modified":"2016-08-04T08:18:55","modified_gmt":"2016-08-04T13:18:55","slug":"using-str2func-for-anonymous-function-handle-creation","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2009\/03\/13\/using-str2func-for-anonymous-function-handle-creation\/","title":{"rendered":"Using str2func for Anonymous Function Handle Creation"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Starting in Release 2009a, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009a\/techdoc\/ref\/str2func.html\"><tt>str2func<\/tt><\/a> lets you create a handle to anonymous function.  Before that, you need to construct an anonymous function from literal strings,\r\n         or using some ugly code involving <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009a\/techdoc\/ref\/eval.html\"><tt>eval<\/tt><\/a>.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">The Past<\/a><\/li>\r\n         <li><a href=\"#4\">Creating an Anonymous Function Inside a Function<\/a><\/li>\r\n         <li><a href=\"#7\">Does This Help?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>The Past<a name=\"1\"><\/a><\/h3>\r\n   <p>Since the introduction of <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2009a\/techdoc\/matlab_prog\/f4-70115.html\">anonymous functions<\/a> in MATLAB version 7, you could create an anonymous function like this:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">multiplier = 17;\r\nmyfactor = @(x) multiplier*x;<\/pre><p>The applying the function does what you expect.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">x = rand(1,4)\r\ny = myfactor(x)<\/pre><pre style=\"font-style:oblique\">x =\r\n      0.42176      0.91574      0.79221      0.95949\r\ny =\r\n       7.1699       15.568       13.468       16.311\r\n<\/pre><p>I have just created a function that, when applied, multiplies its input by the value defined by <tt>multiplier<\/tt> (its value when <tt>myfactor<\/tt> was created).\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">multiplier = 42\r\ny = myfactor(x)<\/pre><pre style=\"font-style:oblique\">multiplier =\r\n    42\r\ny =\r\n       7.1699       15.568       13.468       16.311\r\n<\/pre><h3>Creating an Anonymous Function Inside a Function<a name=\"4\"><\/a><\/h3>\r\n   <p>Suppose I want to create an anonymous function, inside another function. And the information for the function to create is\r\n      passed into the function.  You can run into a problem if the function inside which you are creating the anonymous function\r\n      happens to have some name, perhaps a subfunction, that is the same as the user input name.  Using a solution involving <tt>eval<\/tt> would pick up the reference to the subfunction instead of the intended function outside the scope of the file.  Here's an\r\n      example.\r\n   <\/p><pre>   function anon = myfun(X,fun)\r\n   anon = str2func(['@(',X,')',fun,'(',X,')']);<\/pre><pre>   function meshgrid\r\n   disp(17)<\/pre><p>What happens if you try to call <tt>myfun<\/tt> with <tt>fun<\/tt> = <tt>'meshgrid'<\/tt><\/p><pre> anon = myfun('x,y','meshgrid');<\/pre><p>If you now use <tt>anon<\/tt>, e.g., <tt>[a,b] = anon(x,y)<\/tt>, you will get the version of <tt>meshgrid<\/tt> on your path, not the one local to <tt>myfun<\/tt>.  If instead you change <tt>str2func<\/tt> in <tt>myfun<\/tt> to <tt>eval<\/tt>, then <tt>anon(x,y)<\/tt> will use the subfunction <tt>meshgrid<\/tt>, which you most likely didn't intend, and certainly a user of your code would be surprised.\r\n   <\/p>\r\n   <h3>Does This Help?<a name=\"7\"><\/a><\/h3>\r\n   <p>Does this extended functionality in <tt>str2func<\/tt> help you with any of your applications?  Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=175#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_8f5d524eb3cc4c2887d893b75f7b4548() {\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='8f5d524eb3cc4c2887d893b75f7b4548 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 8f5d524eb3cc4c2887d893b75f7b4548';\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 2009 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_8f5d524eb3cc4c2887d893b75f7b4548()\"><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.8<br><\/p>\r\n<\/div>\r\n<!--\r\n8f5d524eb3cc4c2887d893b75f7b4548 ##### SOURCE BEGIN #####\r\n%% Using str2func for Anonymous Function Handle Creation\r\n% Starting in\r\n% <https:\/\/www.mathworks.com\/help\/relnotes\/index.htmlrelnotes.html Release 2009a>,\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009a\/techdoc\/ref\/str2func.html |str2func|>\r\n% lets you create a handle to anonymous function.  Before that, you need to\r\n% construct an anonymous function from literal strings, or using some ugly\r\n% code involving \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009a\/techdoc\/ref\/eval.html |eval|>.\r\n%% The Past\r\n% Since the introduction of \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2009a\/techdoc\/matlab_prog\/f4-70115.html anonymous functions>\r\n% in MATLAB version 7, you could create an anonymous function like this:\r\nmultiplier = 17;\r\nmyfactor = @(x) multiplier*x;\r\n%%\r\n% The applying the function does what you expect.\r\nx = rand(1,4)\r\ny = myfactor(x)\r\n%%\r\n% I have just created a function that, when applied, multiplies its input\r\n% by the value defined by |multiplier| (its value when |myfactor| was\r\n% created).\r\nmultiplier = 42\r\ny = myfactor(x)\r\n%% Creating an Anonymous Function Inside a Function\r\n% Suppose I want to create an anonymous function, inside another function.\r\n% And the information for the function to create is passed into the\r\n% function.  You can run into a problem if the function inside which you\r\n% are creating the anonymous function happens to have some name, perhaps a\r\n% subfunction, that is the same as the user input name.  Using a solution\r\n% involving |eval| would pick up the reference to the subfunction instead\r\n% of the intended function outside the scope of the file.  Here's an\r\n% example.\r\n%%\r\n% \r\n%     function anon = myfun(X,fun)\r\n%     anon = str2func(['@(',X,')',fun,'(',X,')']);\r\n% \r\n%     function meshgrid\r\n%     disp(17)\r\n%% \r\n% What happens if you try to call |myfun| with |fun| = |'meshgrid'|\r\n% \r\n%   anon = myfun('x,y','meshgrid');\r\n% \r\n% If you now use |anon|, e.g., |[a,b] = anon(x,y)|, you will get the version\r\n% of |meshgrid| on your path, not the one local to |myfun|.  If instead\r\n% you change |str2func| in |myfun| to |eval|, then |anon(x,y)| will use \r\n% the subfunction |meshgrid|, which you most likely didn't intend, and\r\n% certainly a user of your code would be surprised.\r\n%% Does This Help?\r\n% Does this extended functionality in |str2func| help you with any of your\r\n% applications?  Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=175#respond here>.\r\n##### SOURCE END ##### 8f5d524eb3cc4c2887d893b75f7b4548\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Starting in Release 2009a, str2func lets you create a handle to anonymous function.  Before that, you need to construct an anonymous function from literal strings,\r\n         or using... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2009\/03\/13\/using-str2func-for-anonymous-function-handle-creation\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3,6],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/175"}],"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=175"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/175\/revisions"}],"predecessor-version":[{"id":1937,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/175\/revisions\/1937"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=175"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=175"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=175"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}