Average across structures and fields

18 views (last 30 days)
Josh Tome
Josh Tome on 12 Dec 2022
Commented: Jan on 14 Dec 2022
Hello, I currently have a set of data that is organized into a main structure with 3 fields (walking_01, walking_02, walking_03). Each of those 3 fields has a sub-structure with 101 fields (LHipAngles, LKneeAngles, etc.). Each of these 101 fields are made up of a double array containing 101 rows x any number of columns. I would like to find the average of each of the 101 fields across all of the main structure's fields (i.e. average of LHipAngles across walking_01, walking_02, and walking_03).

Answers (1)

Jan
Jan on 12 Dec 2022
It was a bad idea to hide an index in the field names as in walking_01. Using an array with a real index is smarter. This is fixed easily:
ModOutLStride_x.walking = cat(1, ModOutLStride_x.walking_01, ...
ModOutLStride_x.walking_02, ...
ModOutLStride_x.walking_03));
By the way, the "L" in the name of the structure looks like you hide the information about the side in the name of the variable. The code is more flexible, if you store the side information separately.
After the above creation of the array:
Data = ModOutLStride_x; % Abbreviation
keyList = fieldnames(Data.walking(1));
nCycle = numel(Data.walking);
for iKey = 1:numel(keyList)
key = keyList{iKey};
value = 0;
for iCycle = 1:nCycle
value = value + Data.walking(iCycle).(key);
end
Data.mean.(key) = value / nCycle;
end
  2 Comments
Josh Tome
Josh Tome on 13 Dec 2022
Edited: Josh Tome on 13 Dec 2022
Thank you. I was able to get this to work but I've changed my approach on how I'd like to process this data. I instead would like to merge each variable (i.e. LHipAngles) across all walking trials (walking_01, walking_02, and walking_03), and then take the average. This will allow me to export all of the individual arrays so that I can inspect them later and remove outliers.
I know this can be done using the code below, but I just need to figure out how to write it into a for loop for each variable across each trial
horzcat(ModOutLstride_x.walking_01.LHipAngles,ModOutLstride_x.walking_02.LHipAngles,ModOutLstride_x.walking_03.LHipAngles)
Jan
Jan on 14 Dec 2022
My code sums up these variables, and you want to concatenate them. So you can modify my code easily:
...
valueC = cell(1, nCycle);
for iCycle = 1:nCycle
valueC{iCycle} = Data.walking(iCycle).(key);
end
Data.All.(key) = cat(2, valueC{:}); % Or maybe cat along 1st or 3rd dim?
...

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!