Effacer les filtres
Effacer les filtres

How do I take an average of fields in a structure?

93 vues (au cours des 30 derniers jours)
Liz Web
Liz Web le 23 Mar 2018
I have 3 fields in a structure that I want to take the average and standard deviation of. What is the simplest way to do this?
  1 commentaire
Espen Mikkelsen
Espen Mikkelsen le 24 Mar 2018
could you give one example of your data?

Connectez-vous pour commenter.

Réponse acceptée

Image Analyst
Image Analyst le 24 Mar 2018
One way
totalMean = mean([BindingDataToSave.TotalVirusesBound]);
totalStdDev = std([BindingDataToSave.TotalVirusesBound]);
Similar for the other 2 fields. Walter's method is probably better since it gives you all 3 means in one shot.

Plus de réponses (2)

Walter Roberson
Walter Roberson le 24 Mar 2018
means = structfun(@mean, BindingDataToSave, 'uniform', 0);
stds = structfun(@std, BindingDataToSave, 'uniform', 0);

George Abrahams
George Abrahams le 30 Déc 2022
An improvement over Walter's answer would be to use my fieldfun function on File Exchange / GitHub, which outputs a structure with the same fields as the input structure(s). That means that you can index the means and standard deviations without knowing the order of the fields (effectively columns in your attached image).
rng(1,'twister')
BindingDataToSave = struct( 'TotalVirusesBound', num2cell(rand(26,1)), ...
'NumberGoodViruses', num2cell(rand(26,1)), 'NumberBadViruses', ...
num2cell(rand(26,1)) );
fieldfun( @(varargin) mean([varargin{:}]), BindingDataToSave )
% ans = struct with fields:
% TotalVirusesBound: 0.4574
% NumberGoodViruses: 0.4675
% NumberBadViruses: 0.4530
Although, you should probably also consider using a table and not a structure.
BindingDataToSave = struct2table( BindingDataToSave );
mean( BindingDataToSave.TotalVirusesBound )
% ans = 0.4574
varfun(@mean,BindingDataToSave)
% ans = 1×3 table
% mean_TotalVirusesBound mean_NumberGoodViruses mean_NumberBadViruses
% 0.45736 0.46752 0.45302

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by