我在MATLAB 2007中找到了一个示例,其中cellfunarrayfun几乎可以互换使用:

>> cellfun(@(c) c, {'one' 'two' 'three'}, 'uniformoutput', 0)
% ans =
%    'one'    'two'    'three'
>> arrayfun(@(c) c, {'one' 'two' 'three'})
% ans =
%    'one'    'two'    'three'


我也可以想到一个arrayfun有效但cellfun无效的示例:

>> arrayfun(@(c) c, [1 2 3])
% ans =
%      1     2     3
>> cellfun(@(c) c, [1 2 3])
% ??? Error using ==> cellfun
% Input #2 expected to be a cell array, was double instead.


我的问题是:在什么情况下cellfun可以工作,而arrayfun不能呢?如果是,请举例说明。如果没有,为什么cellfun甚至需要存在?

最佳答案

有一些内置函数可以在cellfun中按名称引用,但不能以相同的方式在arrayfun中使用。从帮助中:

A = CELLFUN('fun', C), where 'fun' is one of the following strings,
returns a logical or double array A the elements of which are computed
from those of C as follows:

   'isreal'     -- true for cells containing a real array, false
                   otherwise
   'isempty'    -- true for cells containing an empty array, false
                   otherwise
   'islogical'  -- true for cells containing a logical array, false
                   otherwise
   'length'     -- the length of the contents of each cell
   'ndims'      -- the number of dimensions of the contents of each cell
   'prodofsize' -- the number of elements of the contents of each cell


因此cellfun('isreal', {'one' 'two' 'three'})是有效的表达式,但是任何与arrayfun相似的调用都将触发First input must be a function handle错误。

当然,您可以将@isreal@isempty用于arrayfun

至于为什么cellfun仍然存在,我怀疑它是历史的(不要破坏向后兼容性)

关于arrays - 在MATLAB中,cellfun是否总是可替换为arrayfun?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18239129/

10-12 05:27