arrayfun
Applies a function to each element of one or more arrays.
Category: Language Fundamentals > Data Types
Syntax
B = arrayfun(func, A)
Calls func on every element of A and collects the scalar results in an array of the same size.
B = arrayfun(func, A1, ..., An)
Passes corresponding elements of several arrays of the same size.
[B1, ..., Bm] = arrayfun(___)
Collects several outputs of func.
B = arrayfun(___, 'UniformOutput', false)
Returns a cell array so results can be of any size or type.
B = arrayfun(___, 'ErrorHandler', f)
Calls f instead of stopping when func errors on an element.
Description
arrayfun is a loop in disguise: it does not vectorize the computation, but it removes bookkeeping and keeps the result shaped like the input. It is the right tool when func does not work on whole arrays, for instance when it returns text or vectors per element.
With the default UniformOutput every call must return a scalar of the same class; otherwise an error is raised. Use cellfun for cell arrays and structfun for the fields of a struct.
Input arguments
func- Function handle taking as many arguments as there are arrays.
A- Array of any type, including struct arrays.
'UniformOutput'true(default) requires scalar results;falseallows anything and returns a cell array.'ErrorHandler'- Handle receiving an error struct and the inputs; its output replaces the missing result.
Output arguments
B- Array (or cell array) with the same size as the inputs.
Examples
Uniform and cell output
arrayfun(@(x) x^2, 1:4)
c = arrayfun(@(k) k*ones(1, k), 1:3, 'UniformOutput', false)
arrayfun(@(x, y) x + y, [1 2; 3 4], [10 20; 30 40])
ans = 1×4
1 4 9 16
c = 1×3 cell
{[1]} {[2 2]} {[3 3 3]}
ans = 2×2
11 22
33 44
Several outputs
[m, i] = arrayfun(@(k) max([k 3 2]), 1:4)
m = 1×4
3 3 3 4
i = 1×4
2 2 1 1