arrayfun

Evaluates the function func on each element of the array m. Each element is passed into the function individually.

Syntax

R = arrayfun(func, input1)

R = arrayfun(func, input1, input2, ...)

R = arrayfun(..., 'uniformoutput', flag)

R = arrayfun(..., 'errorhandler', errorFunc)

[R1, ...] = arrayfun(...)

Inputs

func
Function to be evaluated.
Type: char | string | handle
input1, input2, ...
Array(s) to be operated on.
Type: double | integer | struct
Dimension: scalar | matrix
flag
Uniform output type which specifies the class of R. By default, flag is 1, with R being a matrix. If flag is 0, R will be a cell.
Type: integer | log
errorFunc
A function to be evaluated if func throws an error. errorFunc accepts an additional input argument err. err is a structure which contains the fields 'index', the index of the element that caused the error and 'message', the error message. The number of outputs of errorFunc must be the same as func's.
Type: char | string | handle

Outputs

R
Resulting output.

Examples

String arrayfun with default options:
arrayfun('max', [1:5], [0 3 5 2 1])
R = [Matrix] 1 x 5
1  3  5  4  5
Function handle arrayfun with default options:
function z = my_func(a, b)
  if (a > b)
  z = a - b;
  else
  z = a+b;
  end
end
m1 = [1:4; 2:5; 3:6];
m2 = [2 5 9 8; 5 2 6 7; 3 6 9 2];
R = arrayfun(@my_func, m1, m2)
R = [Matrix] 3 x 4
3   7  12  12
7   1  10  12
6  10  14   4
arrayfun with UniformOutput option:
R = arrayfun(@(a, b) [a, b], '1234', 'abcd', 'uniformoutput', 0)
R = 
{
  [1,1] 1a
  [1,2] 2b
  [1,3] 3c
  [1,4] 4d
}
arrayfun with multiple outputs:
function [z1, z2] = my_func(a, b)
  z1 = a + b;
  z2 = a*b;
end
[R1, R2] = arrayfun(@my_func, 1:5, 11:15)
R1 = [Matrix] 1 x 5
12  14  16  18  20
R2 = [Matrix] 1 x 5
11  24  39  56  75
arrayfun with an error handling function:
function z = my_func(a)
  z = a.a + str2num(a.b);
end

function z = my_error_func(err, a, b)
  err.index
  err.message
  z = 10;
end
s(1).a = 1;
s(2).a = 2;
s(3).a = 3;
s(1).b = '1';
s(2).b = 2;
s(3).b = '3';
R = arrayfun(@my_func , s, 'errorhandler', @my_error_func)
ans = 2
ans = Error: invalid input in argument 1; must be string
R = [Matrix] 1 x 3
2  10  6