9

I want to apply a function to each element of a cell array -- so I have cellfun for that. However, the function takes two extra arguments (a string and a vector), which I want to keep constant for all the elements of the cell array; i.e. I'd like to do something like:

cellfun(@myfun, cellarray, const1, const2)

meaning:

for i = 1:numel(cellarray),
  myfun(cellarray{i}, const1, const2);
end

Is there some way to do that without creating intermediate cell arrays containing numel(cellarray) copies of const1 and const2?

gnovice
  • 125,304
  • 15
  • 256
  • 359
antony
  • 2,877
  • 4
  • 31
  • 43

2 Answers2

16

You can do this using an anonymous function that calls myfun with the two additional arguments:

cellfun(@(x) myfun(x,const1,const2), cellarray)
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • Currently I'm using this solution, but is there any other? For large arrays it can produce a considerable amount of overhead. Is the only alternative to create an array of copies of `const1, const2` (not a good alternativ)? – embert Sep 20 '14 at 08:11
  • 1
    @embert I'm not sure where the extra overhead would be coming from, but perhaps you could use the profiler to find out. I would also try out the for loop alternative in the question, since for loops don't incur the sort of penalty they used to in MATLAB (sometimes they are even the fastest alternative). – gnovice Sep 20 '14 at 19:52
4

Another trick is to use ARRAYFUN on the indices:

arrayfun(@(k) myfun(cellarray{k},const1,const2), 1:numel(cellarray))

if the return values of myfun are not scalars, you might want to set the 'UniformOutput',false option.

Amro
  • 123,847
  • 25
  • 243
  • 454