Averaging data

5 views (last 30 days)
Marcel
Marcel on 9 Mar 2012
Hi,
How to average 1s long samples of a data set? I have a data in a form t = [0 1 2 3...5000...10000 ...10000] d = [5 5 5 4... 1... 6...8 ]
where t represents milliseconds and d represents specific values for each millisecond. I'd like to have t in seconds so then values from d should be averaged every 999ms. I mean e.g. for t=0s d=5, for t=1s, d should be an average of values form 1 to 999ms and so on.
Thanks for help.

Accepted Answer

Wayne King
Wayne King on 9 Mar 2012
One of many ways:
If the spacing between elements in your d vector is 1 msec, then you can reshape the data vector into a matrix with columns equal to 1000 rows and take the average of the columns.
Of course, if the vector does not reshape evenly in equal-length columns, you have to think about what to do at the end.
Assume two seconds of data:
x = randn(2000,1);
x1 = reshape(x,1000,2);
mean(x1)
Another possibility is to create a simple function to do it and call that function from the command line. You have to save the function as nway.m in a folder that is on your MATLAB path.
function B = nway(A,n)
% Compute average of every N elements of A and put them in B.
if ((mod(numel(A),n) == 0) && (n>=1 && n<=numel(A)))
B = ones(1,numel(A)/n);
k = 1;
for i = 1 : numel(A)/n
B(i) = mean(A(k + (0:n-1)));
k = k + n;
end
else
error('n <= 0 or does not divide number of elements evenly');
end
then,
>>meanz = nway(x,1000);
gives you the same result that I showed above.
  1 Comment
Marcel
Marcel on 9 Mar 2012
Thanks very much for your help

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!