Conditioned moving average window

3 views (last 30 days)
Thanh Vu
Thanh Vu on 13 Jul 2017
Commented: Thanh Vu on 13 Jul 2017
Hi everyone, I'm a newbie to Matlab. I'm running a simulation and we're trying to analyse the moving average path length. As in the attached excel, the first column is the time elapsed and the second one is the path length. How do we plot an average moving window of 30 ticks, despite that some time ticks may have more than 1 path length? Thanks.

Answers (1)

Steven Lord
Steven Lord on 13 Jul 2017
If I understand your question correctly, I think you want to use the movmean function with the 'SamplePoints' option.
rng default
t = sort(rand(10, 1));
x = randi(10, 10, 1);
m = movmean(x, [0.25 0.125], 'SamplePoints', t);
results = table((1:10).', t, t-0.25, t+0.125, x, m, ...
'VariableNames', {'row', 't', 't_before', 't_after', 'x', 'movingAverage'})
As an example, consider row 3 of the results table. Row 3's movingAverage should consist of the mean of the values of x in all rows whose t values are between the values of t_before and t_after in row 3. For this sample code, I used rng default so you will receive the same t and x vectors as I did and thus I know that the first three rows contribute to row 3's movingAverage:
results{3, 'movingAverage'} - mean(x(1:3)) % should be 0
  1 Comment
Thanh Vu
Thanh Vu on 13 Jul 2017
Hi, thank you for your fast reply, sorry it took me a while to understand it. Yes, it does work, though not entirely. If you look in the excel data, some t may have more than 1 x data, resulting in 2 or 3 rows with the same t, and the program ran this error:
'SamplePoints' value contains duplicates.
Is there some way to fix this issue? Otherwise your code was terrific, thank you very much.
P.S.: can you clarify the '[0.25 0.125]' part in the moving mean? I'm not sure if I understand it fully. Thanks

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!