How to calculate mean of multiple arrays

8 views (last 30 days)
I have a 12263x1 cell called rep with arrays that range from 784x1 to 1134x1 . Within these arrays I have data corresponding to pupil size measured in arbitrary units at time points measured in ms (1-784ms) . I want to create the mean pupil trace for all 12263 trials however I am having trouble. Is it even possible to perform an average trace if the trials are diffrent lengths ?
I have been trying this code...
for i =1:size(rep)
m(i)= mean (pupil{:,1}{i,1})
end
however this returns 12263 answers, when I really want the mean at each time point for the pupil trials where there should be at most 1134 data points!
Thanks in advance for your help !
  1 Comment
James Tursa
James Tursa on 4 Dec 2018
Edited: James Tursa on 4 Dec 2018
So, the first 784 elements of the result would be the mean of 12263 data points, but the remaining result elements would be the mean of fewer data points (because some of the vectors do not have enough elements)? Is that what you want to do? I.e., the result will contain 1134 elements, and each of these elements will be the mean of a varying number of values depending on the length of the individual vectors in your cell array?

Sign in to comment.

Accepted Answer

Jos (10584)
Jos (10584) on 5 Dec 2018
If I read your question to the letter, you have 12263 recordings of pupil sizes. Each recording lasted 784 ms. Recoring frequency varied between 1000 Hz and (1134/784)*1000 Hz, resulting in different number of samples between recordings ...
In this case: resample each recording to a the same timestampes using INTERP1 (or resample or something along these lines); concatenate all cells using CAT and get the mean
MyFun = @(x) interp1(linspace(1,784,numel(x)), x, 1:784) ;
pupil_resampled = cellfun(MyFun, pupil, 'un', 0) ;
pupil_mean = mean(cat(2, pupil_resampled), 2)
If you have a single sample frequency but sample durations vary, try concatenating using, for instance, PADCAT, which pads shorter arrays with NaNs and use nanmean
pupil_padded = padcat(pupil{:}) ;
pupil_mean = nanmean(pupil_padded, 2)
You might want to tweak the dimension arguments for mean and nanmean depending on the oriention of your pupil cells (all row or column vectors)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!