dustynrobots
dustynrobots

Reputation: 311

how to find mean of columns in nested structure in MATLAB

I've organized some data into a nested structure that includes several subjects, 4-5 trials per subject, then identifying data like height, joint torque over a gait cycle, etc. So, for example:

subject(2).trial(4).torque

gives a matrix of joint torques for the 4th trial of subject 2, where the torque matrix columns represent degrees of freedom (hip, knee, etc.) and the rows represent time increments from 0 through 100% of a stride. What I want to do is take the mean of 5 trials for each degree of freedom and use that to represent the subject (for that degree of freedom). When I try to do it like this for the 1st degree of freedom:

for i = 2:24
    numTrialsThisSubject = size(subject(i).trial, 2);
    subject(i).torque = mean(subject(i).trial(1:numTrialsThisSubject).torque(:,1), 2);
end

I get this error:

??? Scalar index required for this type of multi-level indexing.

I know I can use a nested for loop to loop through the trials, store them in a temp matrix, then take the mean of the temp columns, but I'd like to avoid creating another variable for the temp matrix if I can. Is this possible?

Upvotes: 2

Views: 992

Answers (2)

dustynrobots
dustynrobots

Reputation: 311

As mentioned above in my comment, adding another loop and temp variable turned out to be the simplest execution.

Upvotes: 0

O. Th. B.
O. Th. B.

Reputation: 1353

You can use a combination of deal() and cell2mat().

Try this (use the built-in debugger to run through the code to see how it works):

for subject_k = 2:24
    % create temporary cell array for holding the matrices:
    temp_torques = cell(length(subject(subject_k).trial), 1);

    % deal the matrices from all the trials (copy to temp_torques):
    [temp_torques{:}] = deal(subject(subject_k).trial.torque);

    % convert to a matrix and concatenate all matrices over rows:
    temp_torques = cell2mat(temp_torques);

    % calculate mean of degree of freedom number 1 for all trials:
    subject(subject_k).torque = mean(temp_torques(:,1));
end

Notice that I use subject_k for the subject counter variable. Be careful with using i and j in MATLAB as names of variables, as they are already defined as 0 + 1.000i (complex number).

Upvotes: 1

Related Questions