Matlab: arrayfun, cellfun, spfun and structfun vs. simple for-loop

It really depends on what you call ‘performance’ 🙂

If you mean minimum execution time, well, sometimes *fun are faster (for example, cellfun('isempty', ...); (yes, string argument!) for sure beats the loop version). Sometimes a loop is faster. If you’re on a Matlab version < 2006, go for the *fun functions by default. If you’re on anything more recent, go for the loops by default. You’ll still always have to profile to find out which one’s faster.

As noted by Amro, if you have a GPU capable of doing FP arithmetic, and a recent version of Matlab that supports GpGPU, then a call to arrayfun for gpuArray inputs will be massively-parallelized. However, no general statements can be made regardnig execution time; for smaller arrays, or absolutely humungous ones, the overhead of copying everything over to the GPU might undo any benefit of parallelizing the computations, so…profiling is really the only way to know for sure.

If you mean minimum coding time, then I’d say it’s usually faster to code in terms of *fun as long as the operations are simple. For anything complex it’s usually better to go for the loop.

If you mean optimum readability and thus minimum time required for maintenance and implementation of changes in a professional context, for sure, go for the loop.

At this point in time, there’s not really a clear-cut simple answer to your question 🙂

Leave a Comment