Problem 43686. Apply Function to Each Field of a Structure Array: Part 2
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 structure array c of the same size and same fields as s, where each field of the structure element of c stores the result of f applied to the same field of the relevant structure element in s. The structfun2 must preserve the behavior of structfun for scalar structure input. That is, when s is a scalar structure, your output reduces to c = structfun(f,s,'UniformOutput',false). No assumption on f is needed in this problem.
Example:
s = struct('f1',{1, [3 4]; 1, [5 6]},'f2',{[1 2], 2; [3 4 5], [2 5]});
f = @numel;
c = struct('f1',{1, 2; 1, 2},'f2',{2, 1; 3, 2});
Related problems in this series:
Solution Stats
Problem Comments
-
1 Comment
Why is part 2 easier than part 1?
Solution Comments
Show commentsProblem Recent Solvers23
Suggested Problems
-
Test if a Number is a Palindrome without using any String Operations
246 Solvers
-
Project Euler: Problem 6, Natural numbers, squares and sums.
2500 Solvers
-
4959 Solvers
-
Numbers spiral diagonals (Part 1)
285 Solvers
-
String Array Basics, Part 4: Convert String Array with Missing Values to Cell Array
114 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!