TExcelTAD
Home › MATLAB / Octave › arrayfun & cellfun

arrayfun & cellfun

arrayfun and cellfun apply a function to every element of an array or every cell of a cell array and collect the results. They replace short loops with a single expression, and they're especially useful with cell arrays, which most math functions can't process directly.

arrayfun

arrayfun(f, A) calls f(A(k)) for each element and returns an array of the same size:

matlab · try it yourself
n = 1:6;
digitsCount = arrayfun(@(x) numel(num2str(x^5)), n)
isPrime = arrayfun(@(x) isprime(x), [2 9 11 15])
digitsCount =

   1   2   3   4   4   4

isPrime =

  1  0  1  0

Many functions are already vectorised (isprime(A) works directly), so check that first; arrayfun is for functions that only handle one value at a time.

cellfun

cellfun(f, C) calls f(C{k}) for each cell. Common built-ins can also be passed by name as text ('isempty', 'length'), which is a little faster:

matlab · try it yourself
words = {'kiwi', 'banana', '', 'fig', 'cherry'};
lens = cellfun(@length, words)
empty = cellfun('isempty', words)
longOnes = words(lens > 4)
lens =

   4   6   0   3   6

empty =

  0  0  1  0  0

longOnes =
{
  [1,1] = banana
  [1,2] = cherry
}

Non-scalar results: UniformOutput

By default every call must return a single scalar so the results fit in a normal array. If the function returns text or arrays of varying size, pass 'UniformOutput', false to get a cell array back:

matlab · try it yourself
words = {'kiwi', 'banana', 'fig'};
try
    up = cellfun(@upper, words);
catch err
    disp('Fails: upper returns text, not a scalar')
end
up = cellfun(@upper, words, 'UniformOutput', false)
firstTwo = cellfun(@(w) w(1:min(2, end)), words, 'UniformOutput', false);
fprintf('%s ', firstTwo{:});
fprintf('\n');
squares = arrayfun(@(n) (1:n).^2, 1:3, 'UniformOutput', false);
disp(squares{3})
Fails: upper returns text, not a scalar
up =
{
  [1,1] = KIWI
  [1,2] = BANANA
  [1,3] = FIG
}

ki ba fi 
   1   4   9

w(1:min(2, end)) takes up to two characters, so it also works for words shorter than two letters.

Several inputs and outputs

With several input arrays (all the same size), the function receives one element from each. With several outputs, each comes back as a separate array:

matlab · try it yourself
widths = [2 3 4];
heights = [5 1 2];
areas = arrayfun(@(w, h) w * h, widths, heights)

data = {[3 9 1], [7 7], [10 2 8 4]};
[lo, hi] = cellfun(@(v) deal(min(v), max(v)), data)
areas =

   10    3    8

lo =

   1   7   2

hi =

    9    7   10

deal returns its inputs as separate outputs, a handy trick to make an anonymous function return two values.

Applying a function to struct arrays

arrayfun also iterates over struct arrays, which is a compact way to extract or compute something per record:

matlab · try it yourself
s(1).name = 'Ana'; s(1).scores = [80 90];
s(2).name = 'Ben'; s(2).scores = [70 65 75];
s(3).name = 'Cy';  s(3).scores = 100;
avg = arrayfun(@(r) mean(r.scores), s)
labels = arrayfun(@(r) sprintf('%s (%d)', r.name, numel(r.scores)), s, 'UniformOutput', false);
disp(strjoin(labels, ', '))
avg =

    85    70   100

Ana (2), Ben (3), Cy (1)

Loops or arrayfun?

arrayfun/cellfun aren't automatically faster than a loop; their advantage is conciseness. Use them for short element-wise transformations, especially on cell arrays. When the body needs several statements, a loop (or a local function passed as a handle) is clearer.

Test yourself

What does cellfun(@numel, {'ab', 'cde', ''}) return?

  1. [2 3 0]
  2. 3
  3. {'ab','cde',''}
  4. An error

When do you need 'UniformOutput', false?

  1. When the input is a cell array
  2. When the function returns something other than a scalar per element
  3. When there are several inputs
  4. Always with arrayfun

What is arrayfun(@(x) x * 2, [1 2 3])?

  1. [2 4 6]
  2. {2, 4, 6}
  3. 12
  4. [1 2 3 1 2 3]