In MATLAB, is cellfun always replaceable with arrayfun?

arrays, matlab

Solution

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

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.

Of course, you can just use `@isreal` or `@isempty` for `arrayfun`

As for why `cellfun` still exists, I suspect it's historical (don't break backward compatibility)

Problem

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' ``` 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. ``` 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?

Original source