MATLAB cellfun lengths of all cells gotcha

Alec Jacobson

January 11, 2015

weblog/

This will be a hard one to remember because it doesn't make a lot of sense at a high level. Suppose you have a long cell array of vectors and you'd like to collect the lengths of each vector. For the sake of the running example you could use:

R = rand(1000000,1);
R = R./sum(R);
lengths = floor(R*numel(M));
lengths = [lengths;numel(M)-sum(lengths)];
C = mat2cell(M,lengths,1);

Then the following equivalently compute then lengths of each vector in the cell:

lengths = cellfun('length',C);
lengths = cellfun(@length,C);
lengths = cellfun(@(x)length(x),C);

The times I see for these are strikingly different:

Elapsed time is 0.022611 seconds.
Elapsed time is 0.817478 seconds.
Elapsed time is 10.252154 seconds.

The first is using a hard coded function inside the cellfun mex file. The second is using a function handle to a builtin function and the last is using an anonymous function wrapping the built in function.