# Mean of a field of a struct

2 views (last 30 days)
FG on 13 Sep 2020
Commented: Ameer Hamza on 15 Sep 2020
As seen in image below, I have a struct of 5 fields. I need to compute the avarege of the HV3, HV5, HV7 and thd in 1st row, then in the second row and so on seperately.. Have a nice weekend.. Matt J on 13 Sep 2020
C=struct2cell(rmfield(S,'name'));
A=cell2mat(reshape(C,1,4,[]));
Averages = reshape( mean(A,1),4,[]).'

FG on 13 Sep 2020
I cant remove names because parameters are shown on the names..
Matt J on 13 Sep 2020
[array2table({S.name}.'),array2table(Averages)]
FG on 14 Sep 2020
Thanks Matt..

Ameer Hamza on 13 Sep 2020
Try something like this
S_new = rmfield(S, 'name');
S_out = arrayfun(@(s) structfun(@mean, s, 'uni', 0), S_new);
[S_out.name] = S.name;

Ameer Hamza on 15 Sep 2020
k here denotes the dimension along which to average. This is not the correct option to use for your case. To average a specific number of elements, try something like this
Ave3 = zeros(size(S));
Ave5 = zeros(size(S));
Ave7 = zeros(size(S));
Avethd = zeros(size(S));
for i=1:length(S)
M3=([S(i).HV3]);
M5=([S(i).HV5]);
M7=([S(i).HV7]);
Mthd = ([S(i).thd]);
Ave3(i)=mean(M3(1660:9870)) ;
Ave5(i)=mean(M5(1660:9870));
Ave7(i)=mean(M7(1660:9870));
Avethd(i)=mean(Mthd(1660:9870));
end
This code also store average values for all the iterations.
FG on 15 Sep 2020
Thank you Ameer.. I just need to write it to excel, job's done !
Ameer Hamza on 15 Sep 2020
I am glad to be of help!