Loren on the Art of MATLAB

Turn ideas into MATLAB

Which Way to Compute: cellfun or for-loop?

Over a long number of years, people have asked whether it's better to use cellfun or a for-loop 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.


Function Handles

If the function handle being called in cellfun takes a long time to evaluate, then the overhead from cellfun will be insignificant. So no big deal to use cellfun in this case.

If the function being called in cellfun is very fast, such as issparse, you will likely be in the situation where the function call overhead dominates. Then use the function directly in a for-loop.

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!

A Selected Set of Functions

When cellfun 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 do use one of the sanctioned fix character arrays (and now scalar strings), however, you will get performance equivalent to the for-loop version.

Here are the strings you can supply as the first input to cellfun and expect high performance (from the Backward Compatibility section in the doc for cellfun:

  • "isempty"
  • "islogical"
  • "isreal"
  • "length"
  • "ndims"
  • "prodofsize"
  • "size"
  • "isclass"

There are some caveats with using these strings, including

  • cellfun does not call any overloaded versions of these functions
  • cellfun('isclass',C,classname) returns logical 1 (true) for each element of C that matches the classname argument. This syntax returns logical 0 (false) for objects that are a subclass of classname

Your Use of cellfun

Do you use cellfun? When and how? With what first arguments? Let us know here.

Published with MATLAB® R2019b

  • print
  • send email


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.