Speed of cellfun in MATLAB

When I started programming in Matlab, I quickly realized that in order to reduce the running time of your code you had to make use of Matlab's handy vectorization features whenever possible. Suddenly I became highly suspicious of loops, which I had airily been using in VBA and other languages, and as a result tried to avoid them as much as I could. However, as the data sets I analysed grew in size and I had to use cell arrays, such as when displaying date strings along with numerical values in a GUI table, it dawned on me that using built-in functions instead of loops may not always result in faster code.

Matlab comes with the built-in cellfun function. It basically applies the same operation on each cell in a cell array. To check whether the individual cells in the cell array are empty, for instance, you can have cellfun run the isempty function on each cell instead of writing a loop to do it. However, there are two ways of using cellfun and one of them is really slow while the other is actually quite fast. You can use the @(x) syntax, which turns out to be slow, and a string syntax, which is faster than loops but only works with few simple functions. This fact is not adequately pointed out in Matlab's documentation, in my opinion.

Continue reading "Speed of cellfun in MATLAB"