Moving Average with Variable Window Size

조회 수: 53 (최근 30일)
ET
ET 2022년 5월 15일
편집: ET 2022년 5월 15일
Say I have a time series with time t and data x. Both are column vectors of length n (where n can be very big).
t is sorted, but not monotonic. The step size between successive times in t is variable (and can be 0).
I'd like to calculate the simple moving average of x, but using a window size based on time, not on the number of elements.
For example, a moving average based on a 10 second window. For every t, it will take an average of the last 10s of x. But since the timestep sizes are variable, this could mean that the number of previous elements of x being averaged also varies.
I know how to do this using a loop through t, but that would be very slow considering n can be hundreds of thousands to millions of points.
Is there a clever way to do this without a loop?

채택된 답변

Steven Lord
Steven Lord 2022년 5월 15일
See the "Sample Points for Moving Average" example in the documentation page for movmean. While that example has uniformly spaced sample points, you could use non-uniformly spaced sample points.
  댓글 수: 1
ET
ET 2022년 5월 15일
편집: ET 2022년 5월 15일
Nice, this worked. Thank you!
t = 0 + cumsum(rand(10,1));
x = 3*t;
t = seconds(t);
% Loop method
xm = NaN(size(t));
windowSize = seconds(1.1); % arbitrary size
for k = 1:length(t)
id = find(t(1:k) >= (t(k)-windowSize));
if isempty(id)
continue
end
xm(k) = mean(x(id));
clear id
end
% movmean method
xm2 = movmean(x,[windowSize,0],'SamplePoints',t)
[seconds(t),x,xm,xm2]

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by