monkeytennis
monkeytennis

Reputation: 928

Finding means from fields in a structure without for loop

I have data from an experiment in a structure like this:

data.subject.trial

I need to find the means for scores on trials across all participants (e.g. what is the mean score of all participants on trial x?).

I can get there using a for loop as below but it feels like there should be an easier one-liner to achieve the same thing (values in "trial" are numeric in this instance). Any tips? Many thanks!

for i = 1:length(data.subject)
    for j = 1:length(data.subject(i).trial)
        a(i,j) = data.subject(i).trial(j);
    end
end
trialMeans = mean(a);

Upvotes: 0

Views: 48

Answers (1)

monkeytennis
monkeytennis

Reputation: 928

I think I've stumbled across an answer to my own question...

A = cell2mat({data.subject.trial}); % Put all scores from all trials into 1 vector 
B = reshape(A,[],length(data.subject))'; % Reshape into rows of however many subjects there are
trialMeans = mean(B);

Thanks!

Upvotes: 1

Related Questions