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
?
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}) .
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)) .
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)
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.
You can do this using an anonymous function that calls myfun
with the two additional arguments:
cellfun(@(x) myfun(x,const1,const2), cellarray)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With