Average across the fields of a structure when each field contains a single value

7 vues (au cours des 30 derniers jours)
Hello,
I have a structure (Sway_dist_COP_Sag) with 3 fields, each containing a single value that I would like to average together. Please see image below. I would like the end result to be in the 2.15 range.
Thanks in advance.

Réponse acceptée

Voss
Voss le 13 Fév 2023
S = struct('arbitrary',1.9623,'field',2.584,'names',1.9125)
S = struct with fields:
arbitrary: 1.9623 field: 2.5840 names: 1.9125
C = struct2cell(S)
C = 3×1 cell array
{[1.9623]} {[2.5840]} {[1.9125]}
result = mean([C{:}])
result = 2.1529
  2 commentaires
Josh Tome
Josh Tome le 13 Fév 2023
Yes, this does seem to work for me. Interestingly though, when I try to combine your two lines of code into one...
result = mean([struct2cell(S){:}])
I get a "Invalid array indexing" error. Is there a reason I have to keep it 2 separate lines?
Stephen23
Stephen23 le 13 Fév 2023
"Is there a reason I have to keep it 2 separate lines?"
Yes: in general MATLAB does not allow arbitrary trailing indexing.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 13 Fév 2023
Try this
% Extract all values for each field into row vectors.
v1 = [Sway_dist_COP_Sag.Con1Pre00standop01]
v2 = [Sway_dist_COP_Sag.Con1Pre00standcl02]
v3 = [Sway_dist_COP_Sag.Con1Pre00stand05_1plate]
% Take the mean of all 3 row vectors strung together.
theMean = mean([v1, v2, v3])
  4 commentaires
Josh Tome
Josh Tome le 13 Fév 2023
Won't the for loop continously make v1 equal to whatever the current fieldname's value is?
Also, sorry to complicate things further, but I forgot to mention that I may in the future have more (or less) than three fields.
Voss
Voss le 13 Fév 2023
"Won't the for loop continously make v1 equal to whatever the current fieldname's value is?"
Yes.
Take a look at my answer and see if it'll work for your purposes.

Connectez-vous pour commenter.

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