structfun
Evaluates the function func on the fields of the structure s. Each field is passed into the function individually.
Syntax
R = structfun(func, input)
R = structfun(..., 'uniformoutput', flag)
R = structfun(..., 'errorhandler', errorFunc)
[R1, ...] = structfun(...)
Inputs
- func
- Function to be evaluated.
- input
- Structure to be operated on.
- 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 struct with the same fields as the input.
- 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.
Outputs
- R
- Resulting output.
Examples
s = struct('a', 1:3, 'b', 5:10, 'c', 1:10);
R = structfun('max', s)
R = [Matrix] 3 x 1
3
10
10
function z = my_func(a)
z = max(a);
end
s = struct('a', 1:3, 'b', 5:10, 'c', 1:10);
R = structfun(@my_func, s)
R = [Matrix] 3 x 1
3
10
10
s = struct('a', 1:3, 'b', [1 4 9; 16 25 36], 'c', [1+2i 2+2i; 3+i 4i]);
R = structfun('sqrt', s, 'uniformoutput', 0)
R = struct [
a: [Matrix] 1 x 3
1.00000 1.41421 1.73205
b: [Matrix] 2 x 3
1 2 3
4 5 6
c: [Matrix] 2 x 2
1.27202 + 0.78615i 1.55377 + 0.64359i
1.75532 + 0.28485i 1.41421 + 1.41421i
]
function [z1, z2] = my_func(a)
z1 = sqrt(a);
z2 = power(a,2);
end
s = struct('a', 1:3, 'b', [1 4 9; 16 25 36]);
[R1, R2] = structfun(@my_func, s, 'uniformoutput', 0)
R1 = struct [
a: [Matrix] 1 x 3
1.00000 1.41421 1.73205
b: [Matrix] 2 x 3
1 2 3
4 5 6
]
R2 = struct [
a: [Matrix] 1 x 3
1 4 9
b: [Matrix] 2 x 3
1 16 81
256 625 1296
]
function z = my_error_func(err, a)
err.index
err.message
z = '';
end
s = struct('a', 'Hello World1', 'b', 'Hello World2', 'c', 1:3);
R = structfun(@(x) strsplit(x), s, 'uniformoutput', 0, 'errorhandler', @my_error_func)
ans = 3
ans = Error: invalid input in argument 1; type must be string
R = struct [
a:
{
[1,1] Hello
[1,2] World1
}
b:
{
[1,1] Hello
[1,2] World2
}
c:
]