MATLAB Answers

Doing averages in blocks for downsampling time series data

79 views (last 30 days)
FW
FW on 11 Apr 2019
Commented: Peter Perkins on 19 Apr 2019
One way to downsample is to do averaging in blocks. I had asked a question here "I would like to downsample data simulated at 200 Hz to 50 Hz by averaging blocks of 4 and plot it versus time. For example, if y=[1,2,3,4,5,6,7,8,9,10,11,......], I would like to do averages of (1,2,3,4), then (5,6,7,8), and so and plot it versus t=[0:1/50:60], so that the downsampled data appears to be sampled at 50 Hz." The answer was
y=[1,2,3,4,5,6,7,8,9,10,11];
out = nanmean(reshape([y(:); nan(mod(-numel(y),4),1)],4,[]));
Is there simpler syntax or smaller steps to achieve the same goal. It works but I was trying to decipher the code for self-teaching purposes.
Thank you.

  0 Comments

Sign in to comment.

Accepted Answer

Peter Perkins
Peter Perkins on 16 Apr 2019
A regular timetable and resample?
>> tt = timetable(rand(12,1),'SampleRate',200)
tt =
12×1 timetable
Time Var1
_________ ________
0 sec 0.72187
0.005 sec 0.49658
0.01 sec 0.053694
0.015 sec 0.44163
0.02 sec 0.51917
0.025 sec 0.77194
0.03 sec 0.065356
0.035 sec 0.44279
0.04 sec 0.97718
0.045 sec 0.46774
0.05 sec 0.32906
0.055 sec 0.44593
>> ttAvg = retime(tt,'regular','mean','SampleRate',50)
ttAvg =
3×1 timetable
Time Var1
________ _______
0 sec 0.42845
0.02 sec 0.44982
0.04 sec 0.55498
then
plot(ttAvg.Time,ttAvg.Var1)

  2 Comments

FW
FW on 18 Apr 2019
Thank you Peter. I get an error. Am I missing something additional in Matlab 2017b?
Invalid parameter name: SampleRate.
Error in AVERAGES_IN_BLOCKS (line 1)
tt = timetable(rand(12,1),'SampleRate',200)
Peter Perkins
Peter Perkins on 19 Apr 2019
R2018a added that parameter. You can do the same thing in earlier releases, you just have to create the time vectors explicitly, such as
t = seconds(0:11)/200)
and
t = seconds((0:2)/50)
You can also use milliseconds if that's easier to think about.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!