Maxim L
Maxim L

Reputation: 209

Mean of fields in a structure using structfun, Matlab

I have a structure in the following format:

A.L1.data = <1000x3 double>
A.L2.data = <1000x3 double>
A.L3.data = <1000x3 double>

I would like to obtain the mean of the first column of all the fields, i.e. one vector of 1000 rows that is the mean of L1, L2 and L3.

I have tried using structfun with the following code:

foo = structfun(@(x) mean(x.data(:,1)), A, 'UniformOutput', false)

However, this gives me the mean (single value) of each first column rather than the mean of all the fields.

If I do:

 foo = structfun(@(x) mean(x.data), A, 'UniformOutput', false)

I obtain the mean of each column for each field.

How should I modify my code?

Upvotes: 0

Views: 1352

Answers (2)

JaBe
JaBe

Reputation: 684

You can access all data of a struct by struct2array.

Get struct firstColumnsOfData with fields L1 L2 L3 with the first columns of data:

firstColumnsOfData = structfun(@(x) x.data(:,1), A, 'UniformOutput', false)

Get mean of each element of L1 L2 L3:

mL123 =  mean(struct2array(firstColumnsOfData')) % transpose to not get mean of each field

Upvotes: 1

houtanb
houtanb

Reputation: 4100

I understand your question to mean that you want the mean of A.L1.data(ii,1), A.L2.data(ii,1), and A.L3.data(ii,1), thereby creating a column vector with 1000 entries. With structfun, I don't see how you can apply it across fields in the structure as this applies the function provided to every field in the structure sequentially.

I think what you want is this:

bar = mean([A.L1.data(:,1) A.L2.data(:,1) A.L3.data(:,1)], 2);

Passing 2 as the second argument to mean provides the mean across the rows as opposed to down the columns.

Upvotes: 1

Related Questions