# apply function to all fields in a structure array

4 views (last 30 days)
checker on 11 May 2020
Edited: per isakson on 12 May 2020
Hi,
I have a structure array of the sort:
sa(1).F1.f1 = 1.1; sa(1).F1.f2 = 1.2;
sa(2).F1.f1 = 2.1; sa(2).F1.f2 = 2.2;
I'd like to find the max of all the fields held in F1 like
f1Max = max(arrayfun(@(x) x.F1.f1, sa));
f2Max = max(arrayfun(@(x) x.F1.f2, sa));
without having to explicity code each of F1's fields. Also prefer not to use eval based on field names. Pretty much thinking there's not really a one liner for this. Hints appreciated.
Chris

per isakson on 12 May 2020
Edited: per isakson on 12 May 2020
Another mix of structfun and arrayfun
>> max( cell2mat( arrayfun( @(S) structfun( @(f) f, S.F1 ), sa, 'uni',false ) ), [], 2 )
ans =
2.1
2.2

#### 1 Comment

checker on 12 May 2020
Ah, just so, thanks!

dpb on 11 May 2020
Why the nested structure? That's where the problem arises---convert to a struct array, S as
>> S=F1
S =
1×2 struct array with fields:
f1
f2
K>> arrayfun(@(s) structfun(@max,s),S,'UniformOutput',false)
ans =
1×2 cell array
{2×1 double} {2×1 double}
>>
If there's some reason this is absolutely mandatory, you can use fieldnames to return the field names of the struct programmatically and iterate that way. eval would not be needed but still awkward.

#### 1 Comment

checker on 12 May 2020
The nested structure results from the design of my parsing and type of data I'm parsing for, so it's hard to avoid.
I appreciate your response but the code does not provide the correct result, under the assumption that S=F1 should actually be S=sa.F1.
S=sa.F1 just pulls sa(1).F1. The rest of the code then pulls the max value of sa(1).F1 for each field (f1 and f2), which are scalars.
mxValues = arrayfun(@(s) structfun(@max,s),S,'UniformOutput',false)
mxValues{1}
ans =
1.1000
1.2000