Problem 43685. Apply Function to Each Field of a Structure Array: Part 1
The builtin structfun applies a function handle to each field of a scalar structure, but it does not work for structure array. The purpose of this problem is to generalize structfun to enable support for structure array input.
Write your own function structfun2 which accepts a structure array s and a function handle f as the inputs. The output c = structfun2(f,s) is a cell array of the same size as s, with each cell storing the result of f applied to every field of the relevant structure element in s. The structfun2 must preserve the behavior of structfun for scalar structure input. That is, structfun2(f,s) = structfun(f,s) holds for any scalar structure s. The assumption required is that f is a function that returns a scalar, regardless of the input.
Example:
s = struct('f1',{1, [3 4]; 1, [5 6]},'f2',{[1 2], 2; [3 4 5], [2 5]});
f = @numel;
c = {[1;2], [2;1]; [1;3], [2;2]};
Related problems in this series:
Solution Stats
Problem Comments
Solution Comments
Show commentsProblem Recent Solvers30
Suggested Problems
-
Return unique values without sorting
987 Solvers
-
497 Solvers
-
Remove the two elements next to NaN value
692 Solvers
-
Flag largest magnitude swings as they occur
687 Solvers
-
String Array Basics, Part 1: Convert Cell Array to String Array; No Missing Values
1905 Solvers
More from this Author28
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!