Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 634
antony Avatar asked Jul 19 '10 13:07

antony


People also ask

How do I use Cellfun in Matlab?

Description. A = cellfun( func , C ) applies the function func to the contents of each cell of cell array C , one cell at a time. cellfun then concatenates the outputs from func into the output array A , so that for the i th element of C , A(i) = func(C{i}) .

What does Arrayfun mean in Matlab?

B = arrayfun( func , A ) applies the function func to the elements of A , one element at a time. arrayfun then concatenates the outputs from func into the output array B , so that for the i th element of A , B(i) = func(A(i)) .

How do you use a mat2cell?

c = mat2cell(x,r) divides up an array x by returning a single column cell array containing full rows of x . The sum of the element values in vector r must equal the number of rows of x . The elements of r determine the size of each cell in c , subject to the following formula for i = 1:length(r) : size(c{i},1) == r(i)

How do you change a cell to an array in Matlab?

A = cell2mat( C ) converts a cell array into an ordinary array. The elements of the cell array must all contain the same data type, and the resulting array is of that data type.


2 Answers

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

cellfun(@(x) myfun(x,const1,const2), cellarray)
like image 122
gnovice Avatar answered Oct 02 '22 17:10

gnovice


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.

like image 45
Amro Avatar answered Oct 02 '22 18:10

Amro