Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 491
Shai Avatar asked Apr 22 '13 09:04

Shai


People also ask

Is Arrayfun faster than for loop Matlab?

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.

Is Cellfun faster than for loop Matlab?

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.

Is Arrayfun faster?

arrayfun can be significantly slower than an explicit loop in matlab.

What does Arrayfun mean 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)) .


1 Answers

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 :)

like image 50
Rody Oldenhuis Avatar answered Nov 04 '22 08:11

Rody Oldenhuis