How tho find the max value in a struct?

Hi,
I made a 1x1 struct with 5 fields. The struct consists of a column of fields and a column of values. How do I find the highest value? And if found, the field that belongs to this highest value?

 Accepted Answer

[maxval, maxidx] = structfun(@max, YourStructure);
fn = fieldnames(YourStructure);
which_field_had_max = fn{maxidx};

More Answers (1)

Ameer Hamza
Ameer Hamza on 6 May 2020
Edited: Ameer Hamza on 6 May 2020
Something like this
s.a = 1;
s.b = 9;
s.c = 5;
names = fieldnames(s);
[val, idx] = max(struct2array(s));
max_fieldname = names(idx);
Result
>> val
val =
9
>> max_fieldname
max_fieldname =
1×1 cell array
{'b'}

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!