I can think of a few ways. First, I generate some bogus data through
A = cellfun(@(~)rand(2,1), cell(1000), 'uni', false);
B = rand(2);
Cellfun
As you said, this is what you want to avoid. In any case I'll include it here for comparison:
C = cellfun(@(x)B*x, A, 'UniformOutput',false);
It is slow because of the anonymous function involved. Cellfun with a built-in string function (see help cellfun) is raging fast, however, anonymous functions force the execution to pass by the Matlab interpreter on each and every iteration. Although this can somewhat be made more efficient by JIT, it's far from optimal.
Cell-expansion, num2cell, reshape
The idea: expand the cell into a 2x1000 matrix, carry out the multiplication, and cast the results back into a cell array of the right size. Although elegant in principle, when put in practice it becomes a bit of a mess:
C = reshape( num2cell(B*[A{:}],1), size(A) );
Note that the intermediate 2x1000 temporary is a bit of a waste from a memory-footprint point of view...also, the pass through num2cell (which is non-builtin) and 'useless' reshape slow down the execution quite a bit.
For loop
A loop is simplest to read, simplest to implement. Small memory footprint, good for acceleration by JIT, etc.
C = cell(size(A));
for ii = 1:numel(A)
C{ii} = B*A{ii};
end
It's only drawback really is its bad reputation :)
Comparison
And now for the kicker: which one is fastest?
tic
C = cellfun(@(x)B*x, A, 'uni',false);
toc
tic
C = reshape( num2cell(B*[A{:}],1), size(A) );
toc
tic
C = cell(size(A));
for ii = 1:numel(A)
C{ii} = B*A{ii};
end
toc
Results:
Elapsed time is 4.738791 seconds. % cellfun
Elapsed time is 4.161515 seconds. % cell expansion, num2cell, reshape
Elapsed time is 3.808822 seconds. % loop
Conclusion: loops are not evil anymore since the introduction of JIT compilation in R2008; don't try to avoid them by default.