问题描述
我发现在2007年MATLAB的例子,其中 cellfun
和 arrayfun
几乎可以互换使用:
I found an example in MATLAB 2007 in which cellfun
and arrayfun
can nearly be used interchangeably:
>> cellfun(@(c) c, {'one' 'two' 'three'}, 'uniformoutput', 0)
% ans =
% 'one' 'two' 'three'
>> arrayfun(@(c) c, {'one' 'two' 'three'})
% ans =
% 'one' 'two' 'three'
我也能想到,其中 arrayfun
工作,但一个例子 cellfun
并不:
I can also think of an example where arrayfun
works but cellfun
does not:
>> 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
甚至有存在的必要?
My question is this: are there any situations in which cellfun
works but arrayfun
does not? If yes, please give examples. If no, why does cellfun
even need to exist?
推荐答案
有可以通过名称在 cellfun
引用,但不能使用一些内置功能在 arrayfun
以同样的方式。从帮助:
There are a few built-in functions that can be referenced by name in cellfun
but cannot be used in the same way in arrayfun
. From the help:
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('伊斯雷尔',{一二三化})
是一个有效的前pression,但任何类似的电话 arrayfun
将触发首先输入必须是一个函数句柄
错误。
So cellfun('isreal', {'one' 'two' 'three'})
is a valid expression, but any similar call with arrayfun
will trigger the First input must be a function handle
error.
当然,你可以使用 @isreal
或 @isempty
为 arrayfun
Of course, you can just use @isreal
or @isempty
for arrayfun
至于为什么 cellfun
仍然存在,我怀疑这是历史上(不打破向后兼容)
As for why cellfun
still exists, I suspect it's historical (don't break backward compatibility)
这篇关于在MATLAB中,是cellfun总是更换与arrayfun?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!