matlab滑动平均代码
时间: 2023-09-15 12:20:06 浏览: 136
以下是MATLAB中的一个滑动平均代码示例:
```matlab
function avg = sliding_average(data, window_size)
% Computes the sliding average of the input data
% data: input data as a vector
% window_size: size of the sliding window
% Initialize output vector
avg = zeros(size(data));
% Compute the sliding average
for i = 1:length(data)
if i <= window_size
avg(i) = mean(data(1:i));
else
avg(i) = mean(data(i-window_size+1:i));
end
end
end
```
使用示例:
```matlab
% Generate some random data
data = randn(100,1);
% Compute sliding average with window size of 5
window_size = 5;
avg = sliding_average(data, window_size);
% Plot original data and sliding average
plot(data);
hold on;
plot(avg);
legend('Original data', 'Sliding average');
```
该代码将输入数据分成窗口大小的块,并计算每个窗口的平均值。在前`window_size`个数据点中,平均值只由前`i`个数据点计算。在后面的数据点中,平均值从前一个窗口到当前窗口的所有数据点计算。
阅读全文