{"id":3448,"date":"2019-09-25T09:59:28","date_gmt":"2019-09-25T14:59:28","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=3448"},"modified":"2019-09-18T10:06:33","modified_gmt":"2019-09-18T15:06:33","slug":"which-way-to-compute-cellfun-or-for-loop","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2019\/09\/25\/which-way-to-compute-cellfun-or-for-loop\/","title":{"rendered":"Which Way to Compute: cellfun or for-loop?"},"content":{"rendered":"\r\n<div class=\"content\"><!--introduction--><p>Over a long number of years, people have asked whether it's better to use <tt><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/cellfun.html\">cellfun<\/a><\/tt> or a <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/for.html\"><tt>for<\/tt>-loop<\/a> to perform certain computations.  As with so many things in life, the correct answer here is \"it depends\".  Let me give you a bit more insight so you can make good choices.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#8000febb-dee5-4de0-b384-db09f40537b3\">Function Handles<\/a><\/li><li><a href=\"#7f6c2bd3-e54f-4225-92bb-5e118a0f7c3c\">A Selected Set of Functions<\/a><\/li><li><a href=\"#2eb63826-9af9-4292-9f33-30cba0ec2980\">Your Use of cellfun<\/a><\/li><\/ul><\/div><h4>Function Handles<a name=\"8000febb-dee5-4de0-b384-db09f40537b3\"><\/a><\/h4><p>If the function handle being called in <tt>cellfun<\/tt> takes a long time to evaluate, then the overhead from <tt>cellfun<\/tt> will be insignificant. So no big deal to use <tt>cellfun<\/tt> in this case.<\/p><p>If the function being called in <tt>cellfun<\/tt> is very fast, such as <tt>issparse<\/tt>, you will likely be in the situation where the function call overhead dominates.  Then use the function directly in a <tt>for<\/tt>-loop.<\/p><p>If I know the number of inputs and outputs and the function I want to apply elementwise, I generally write an explicit loop. That might not be your preference, however. Remember, you can always put the code you wanted to write into comments!<\/p><h4>A Selected Set of Functions<a name=\"7f6c2bd3-e54f-4225-92bb-5e118a0f7c3c\"><\/a><\/h4><p>When <tt>cellfun<\/tt> was originally written, it could handle a fixed set of character arrays as the first input, with no additional flexibility. Over the years, the functionality has advanced.  If you <b>do<\/b> use one of the sanctioned fix character arrays (and now scalar strings), however, you will get performance equivalent to the <tt>for<\/tt>-loop version.<\/p><p>Here are the strings you can supply as the first input to <tt>cellfun<\/tt> and expect high performance (from the Backward Compatibility section in the doc for <tt>cellfun<\/tt>:<\/p><div><ul><li>\"isempty\"<\/li><li>\"islogical\"<\/li><li>\"isreal\"<\/li><li>\"length\"<\/li><li>\"ndims\"<\/li><li>\"prodofsize\"<\/li><li>\"size\"<\/li><li>\"isclass\"<\/li><\/ul><\/div><p>There are some caveats with using these strings, including<\/p><div><ul><li><tt>cellfun<\/tt> does not call any overloaded versions of these functions<\/li><li><tt>cellfun('isclass',C,classname)<\/tt> returns <tt>logical 1 (true)<\/tt> for each element of <tt>C<\/tt> that matches the <tt>classname argument<\/tt>. This syntax returns <tt>logical 0 (false)<\/tt> for objects that are a subclass of <tt>classname<\/tt><\/li><\/ul><\/div><h4>Your Use of cellfun<a name=\"2eb63826-9af9-4292-9f33-30cba0ec2980\"><\/a><\/h4><p>Do you use <tt>cellfun<\/tt>?  When and how?  With what first arguments?  Let us know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=3448#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_4196faae6be04038a4baaed08fa5e1e5() {\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='4196faae6be04038a4baaed08fa5e1e5 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 4196faae6be04038a4baaed08fa5e1e5';\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_4196faae6be04038a4baaed08fa5e1e5()\"><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\n4196faae6be04038a4baaed08fa5e1e5 ##### SOURCE BEGIN #####\r\n%% Which Way to Compute: cellfun or for-loop?\r\n% Over a long number of years, people have asked whether it's better to use\r\n% |<https:\/\/www.mathworks.com\/help\/matlab\/ref\/cellfun.html cellfun>| or a\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/for.html |for|-loop> to\r\n% perform certain computations.  As with so many things in life, the\r\n% correct answer here is \"it depends\".  Let me give you a bit more insight\r\n% so you can make good choices.\r\n% \r\n%% Function Handles \r\n% If the function handle being called in |cellfun| takes a long time to\r\n% evaluate, then the overhead from |cellfun| will be insignificant. So no\r\n% big deal to use |cellfun| in this case. \r\n%\r\n% If the function being called in |cellfun| is very fast, such as\r\n% |issparse|, you will likely be in the situation where the function call\r\n% overhead dominates.  Then use the function directly in a |for|-loop.\r\n%\r\n% If I know the number of inputs and outputs and the function I want to\r\n% apply elementwise, I generally write an explicit loop. That might not be\r\n% your preference, however. Remember, you can always put the code you\r\n% wanted to write into comments!\r\n\r\n%% A Selected Set of Functions\r\n% When |cellfun| was originally written, it could handle a fixed set of\r\n% character arrays as the first input, with no additional flexibility. Over\r\n% the years, the functionality has advanced.  If you *do* use one of the\r\n% sanctioned fix character arrays (and now scalar strings), however, you\r\n% will get performance equivalent to the |for|-loop version.\r\n% \r\n% Here are the strings you can supply as the first input to |cellfun| and\r\n% expect high performance (from the Backward Compatibility section in the\r\n% doc for |cellfun|:\r\n% \r\n% * \"isempty\"\r\n% * \"islogical\"\r\n% * \"isreal\"\r\n% * \"length\"\r\n% * \"ndims\"\r\n% * \"prodofsize\"\r\n% * \"size\"\r\n% * \"isclass\"\r\n%%\r\n% There are some caveats with using these strings, including \r\n%\r\n% * |cellfun| does not call any overloaded versions of these functions\r\n% * |cellfun('isclass',C,classname)| returns |logical 1 (true)| for each\r\n% element of |C| that matches the |classname argument|. This syntax returns\r\n% |logical 0 (false)| for objects that are a subclass of |classname|\r\n%% Your Use of cellfun\r\n% Do you use |cellfun|?  When and how?  With what first arguments?  Let us\r\n% know <https:\/\/blogs.mathworks.com\/loren\/?p=3448#respond here>.\r\n\r\n\r\n##### SOURCE END ##### 4196faae6be04038a4baaed08fa5e1e5\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>Over a long number of years, people have asked whether it's better to use <tt><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/cellfun.html\">cellfun<\/a><\/tt> or a <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/for.html\"><tt>for<\/tt>-loop<\/a> to perform certain computations.  As with so many things in life, the correct answer here is \"it depends\".  Let me give you a bit more insight so you can make good choices.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2019\/09\/25\/which-way-to-compute-cellfun-or-for-loop\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[17,79,58,2,12],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/3448"}],"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=3448"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/3448\/revisions"}],"predecessor-version":[{"id":3452,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/3448\/revisions\/3452"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=3448"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=3448"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=3448"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}