If performance is a major factor you should avoid using cells, loops or cellfun/arrayfun.
It’s usually much quicker to use a vector operation (assuming this is possible).
The code below expands on Werner’s add example with standard array loop and array operations.
The results are:
- Cell Loop Time – 0.1679
- Cellfun Time – 2.9973
- Loop Array Time – 0.0465
- Array Time – 0.0019
Code:
nTimes = 1000;
nValues = 1000;
myCell = repmat({0},1,nValues);
output = zeros(1,nValues);
% Basic operation
tic;
for k=1:nTimes
for m=1:nValues
output(m) = myCell{m} + 1;
end
end
cell_loop_timeAdd=toc;
fprintf(1,'Cell Loop Time %0.4f\n', cell_loop_timeAdd);
tic;
for k=1:nTimes
output = cellfun(@(in) in+1,myCell);
end
cellfun_timeAdd=toc;
fprintf(1,'Cellfun Time %0.4f\n', cellfun_timeAdd);
myData = repmat(0,1,nValues);
tic;
for k=1:nTimes
for m=1:nValues
output(m) = myData(m) + 1;
end
end
loop_timeAdd=toc;
fprintf(1,'Loop Array Time %0.4f\n', loop_timeAdd);
tic;
for k=1:nTimes
output = myData + 1;
end
array_timeAdd=toc;
fprintf(1,'Array Time %0.4f\n', array_timeAdd);