Dominik
Dominik

Reputation: 792

find max of a array of structures

I've been googling and searching about but have yet to be successful with this. I would like to know the max value in a{1} and a{2} each considering all the fields. Similarly, I'd like to know the mean for each a, also considering all the fields.

a{1}.field1=[1:5];
a{2}.field1=[1:6];
a{1}.field2=[2:8];
a{2}.field2=[2:9];

I was hoping something below in a loop would work:

fn=fieldnames(a{1});
max(a{1}.(fn{:}))
mean(a{1}.(fn{:}))

I assume there is some super efficient way to do this that I am missing...Any suggestions? Thanks

Upvotes: 2

Views: 5521

Answers (2)

nicktruesdale
nicktruesdale

Reputation: 815

Assuming each field in your struct is compatible with the max/mean functions, you can use:

maxima(ii) = max(structfun(@max, a{ii}))
means(ii) = mean(structfun(@mean, a{ii}))

Structfun returns the max/mean of each field in a column vector. The max and mean functions can easily be applied again to find the total max/mean. You may then run this in a loop for a struct array.

Upvotes: 4

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

First off, I think you mean to define a multi-dimensional structure:

a(1).field1=[1:5];
a(2).field1=[1:6];
a(1).field2=[2:8];
a(2).field2=[2:9];

(Note the round brackets instead of the curly braces. Curly braces would give you a cell-array containing two structs). Now, the values you seek:

max_mean = cellfun(@(x)[max(x) mean(x)], {a.field1}, 'UniformOutput', false);

Doing this, will give you the maximim and mean of a(1).field1 in max_mean{1}, and the maximum and mean of a(2).field1 in max_mean{2}.

Doing this for all fields can be done by nesting the cellfun above in another cellfun:

max_means = cellfun(@(x) ...
    cellfun(@(y)[max(y) mean(y)], {a.(x)}, 'UniformOutput', false), ...
    fieldnames(a), 'UniformOutput', false);

so that

max_means{1}{1} % will give you the max's and means of a(1).field1
max_means{1}{2} % will give you the max's and means of a(2).field1
max_means{2}{1} % will give you the max's and means of a(1).field2
max_means{2}{2} % will give you the max's and means of a(2).field2

Play with these functions until you find something that fits your needs.

Upvotes: 4

Related Questions