How to apply cellfun (or arrayfun or structfun) with constant extra input arguments?

antony picture antony · Jul 19, 2010 · Viewed 12.4k times · Source

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?

Answer

gnovice picture gnovice · Jul 19, 2010

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

cellfun(@(x) myfun(x,const1,const2), cellarray)