Which one is better, using all the *fun
functions (arrayfun
, cellfun
, structfun
and spfun
) or simply using for
loop?
What method gives better performance and which methods should be considered better practice in terms of readability of the code?
For example, I tested arrayfun vs a forloop, squaring the elements, and the speed difference was a factor of two. While this is concrete evidence that we should always use for loops instead of arrayfun, it's obvious that the benefit varies.
For the example Tom gave, however, cellfun with string is much faster than a for loop (in answer to the original question). Elapsed time is 0.755874 seconds. Elapsed time is 0.913470 seconds. Elapsed time is 0.021828 seconds.
arrayfun can be significantly slower than an explicit loop in matlab.
B = arrayfun( func , A ) applies the function func to the elements of A , one element at a time. arrayfun then concatenates the outputs from func into the output array B , so that for the i th element of A , B(i) = func(A(i)) .
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With