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

天大地大妈咪最大 提交于 2019-12-03 09:36:49

问题


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?


回答1:


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

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



回答2:


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.



来源:https://stackoverflow.com/questions/3281575/how-to-apply-cellfun-or-arrayfun-or-structfun-with-constant-extra-input-argume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!