{"id":66,"date":"2006-11-17T12:06:09","date_gmt":"2006-11-17T17:06:09","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=66"},"modified":"2017-04-25T11:08:25","modified_gmt":"2017-04-25T16:08:25","slug":"some-ways-to-create-function-handles","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/17\/some-ways-to-create-function-handles\/","title":{"rendered":"Some Ways to Create Function Handles"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I recently was asked the best way to create function handles, given the names of functions.  This came up because I recommended\r\n         that we should generally remove instances of <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/feval.html\"><tt>feval<\/tt><\/a> in our code since it is often not required and adds an extra level of function calls.  I will show you several ways to work\r\n         with a \"list\" of functions and tell you which ones I prefer and why.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Avoiding Function Handles Altogether (Not Recommended)<\/a><\/li>\r\n         <li><a href=\"#2\">First Alternative (Not Recommended)<\/a><\/li>\r\n         <li><a href=\"#3\">Acceptable Methods<\/a><\/li>\r\n         <li><a href=\"#5\">Best Method, When Possible<\/a><\/li>\r\n         <li><a href=\"#6\">Your Preferences?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Avoiding Function Handles Altogether (Not Recommended)<a name=\"1\"><\/a><\/h3>\r\n   <p>As I said above, I recommend not using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/feval.html\"><tt>feval<\/tt><\/a> because it introduces extra function call overhead, and is usually unnecessary.  In addition, code is generally more robust\r\n      with function handles instead of strings for representing functions.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">funcList = {<span style=\"color: #A020F0\">'sin'<\/span>,<span style=\"color: #A020F0\">'cos'<\/span>,<span style=\"color: #A020F0\">'tan'<\/span>};\r\n<span style=\"color: #0000FF\">for<\/span> i=1:numel(funcList)\r\n    f = feval(funcList{i},1.0);\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><h3>First Alternative (Not Recommended)<a name=\"2\"><\/a><\/h3>\r\n   <p>Here's a method that constructs function handles from strings using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/eval.html\"><tt>eval<\/tt><\/a>, a function that has a deservedly bad reputation for most applications (see these two articles: <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=9\">Evading Eval<\/a> and <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=15\">More on Eval<\/a>).\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">funcList = {<span style=\"color: #A020F0\">'sin'<\/span>,<span style=\"color: #A020F0\">'cos'<\/span>,<span style=\"color: #A020F0\">'tan'<\/span>};\r\n<span style=\"color: #0000FF\">for<\/span> i=1:numel(funcList)\r\n    func = eval([<span style=\"color: #A020F0\">'@'<\/span> funcList{i}]);\r\n    f = func(1.0)\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">f =\r\n    0.8415\r\nf =\r\n    0.5403\r\nf =\r\n    1.5574\r\n<\/pre><h3>Acceptable Methods<a name=\"3\"><\/a><\/h3>\r\n   <p>If you have to start off with strings at all, such as having them passed in as arguments, you can convert them immediately\r\n      to function handles and then proceed, by using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/str2func.html\"><tt>str2func<\/tt><\/a>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">funcList = {<span style=\"color: #A020F0\">'sin'<\/span>,<span style=\"color: #A020F0\">'cos'<\/span>,<span style=\"color: #A020F0\">'tan'<\/span>};\r\n<span style=\"color: #0000FF\">for<\/span> i= 1:numel(funcList)\r\n   fh = str2func(funcList{i});\r\n   f = fh(1.0);\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><p>If you have a fixed function list, simply create the function handles to start and use them.  One way is to use <tt>feval<\/tt> and <tt>cellfun<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">funcList = {@sin, @cos, @tan};\r\nvals = repmat({1.0},size(funcList));\r\nf = cellfun(@feval, funcList, vals);<\/pre><h3>Best Method, When Possible<a name=\"5\"><\/a><\/h3>\r\n   <p>My favorite method, when I can choose to create function handles from the start, is to just iterate over the list.  I find\r\n      that more readable than the <tt>cellfun<\/tt> code <b>and<\/b> I get to avoid the extra <tt>feval<\/tt> call.  The expense comes at the for-loop.  Preallocation when you plan to actually use the results (unlike these examples)\r\n      often mitigates the downsides of the loop.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">funcList = {@sin, @cos, @tan};\r\n<span style=\"color: #0000FF\">for<\/span> i = 1:numel(funcList)\r\n   f = funcList{i}(1.0);\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><h3>Your Preferences?<a name=\"6\"><\/a><\/h3>\r\n   <p>I've told you my preferences.  What are yours for creating function handles?  Let me know.<\/p><script language=\"JavaScript\"> \r\n<!--\r\n    function grabCode_ef22b4e4255f447fbc30c000d5d07928() {\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='ef22b4e4255f447fbc30c000d5d07928 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' ef22b4e4255f447fbc30c000d5d07928';\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 2006 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      <\/script>\r\n<noscript>\r\n<em>A Javascript-enabled browser is required to use the \"Get the MATLAB code\" link.<\/em>\r\n<\/noscript>\r\n<p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_ef22b4e4255f447fbc30c000d5d07928()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code<\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.3<br><\/p>\r\n<\/div>\r\n<!--\r\nef22b4e4255f447fbc30c000d5d07928 ##### SOURCE BEGIN #####\r\n%% Some Ways to Create Function Handles\r\n% I recently was asked the best way to create function handles,\r\n% given the names of functions.  This came up because I recommended that we\r\n% should generally remove instances of \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/feval.html |feval|>\r\n% in our code since it is often not required and adds an extra level of\r\n% function calls.  I will show you several ways to work with a \"list\" of\r\n% functions and tell you which ones I prefer and why.\r\n\r\n%% Avoiding Function Handles Altogether (Not Recommended)\r\n% As I said above, I recommend not using <https:\/\/www.mathworks.com\/help\/matlab\/ref\/feval.html |feval|>\r\n% because it introduces extra function call overhead, and is usually\r\n% unnecessary.  In addition, code is generally more robust with function\r\n% handles instead of strings for representing functions.\r\nfuncList = {'sin','cos','tan'};\r\nfor i=1:numel(funcList)\r\n    f = feval(funcList{i},1.0);\r\nend\r\n\r\n%% First Alternative (Not Recommended)\r\n% Here's a method that constructs function handles from strings using \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/eval.html |eval|>, \r\n% a function that has a deservedly bad reputation for most applications (see \r\n% these two articles: <https:\/\/blogs.mathworks.com\/loren\/?p=9 Evading Eval>\r\n% and <https:\/\/blogs.mathworks.com\/loren\/?p=15 More on Eval>).\r\nfuncList = {'sin','cos','tan'};\r\nfor i=1:numel(funcList)\r\n    func = eval(['@' funcList{i}]);\r\n    f = func(1.0)\r\nend\r\n\r\n%% Acceptable Methods\r\n% If you have to start off with strings at all, such as having them passed\r\n% in as arguments, you can convert them immediately to function handles and\r\n% then proceed, by using\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/str2func.html |str2func|>.\r\nfuncList = {'sin','cos','tan'};\r\nfor i= 1:numel(funcList)\r\n   fh = str2func(funcList{i});\r\n   f = fh(1.0);\r\nend\r\n%%\r\n% If you have a fixed function list, simply create the function handles to\r\n% start and use them.  One way is to use |feval| and |cellfun|.\r\nfuncList = {@sin, @cos, @tan};\r\nvals = repmat({1.0},size(funcList));\r\nf = cellfun(@feval, funcList, vals);\r\n\r\n%% Best Method, When Possible\r\n% My favorite method, when I can choose to create function handles from the\r\n% start, is to just iterate over the list.  I find that more readable than\r\n% the |cellfun| code *and* I get to avoid the extra |feval| call.  The\r\n% expense comes at the for-loop.  Preallocation when you plan to actually\r\n% use the results (unlike these examples) often mitigates the downsides of\r\n% the loop.\r\nfuncList = {@sin, @cos, @tan};\r\nfor i = 1:numel(funcList)\r\n   f = funcList{i}(1.0);  \r\nend\r\n%% Your Preferences?\r\n% I've told you my preferences.  What are yours for creating function\r\n% handles?  <http:?p=66#respond Let me know.>\r\n% \r\n##### SOURCE END ##### ef22b4e4255f447fbc30c000d5d07928\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I recently was asked the best way to create function handles, given the names of functions.  This came up because I recommended\r\n         that we should generally remove instances of... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/17\/some-ways-to-create-function-handles\/\">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,3,15],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/66"}],"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=66"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/66\/revisions"}],"predecessor-version":[{"id":2313,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/66\/revisions\/2313"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=66"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=66"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=66"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}