数字信号升采样降采样matlab例程
时间: 2024-10-17 16:01:39 浏览: 77
在MATLAB中,数字信号处理通常涉及到采样和量化等操作。升采样和降采样是改变信号样本率的基本步骤。以下是简单的例子:
**升采样 (Upsampling):**
```matlab
function upsampled_signal = up_sampling(x, ratio)
% 输入:原始信号x,升采样的比率ratio
N = length(x);
upsampled_ratio = ratio;
upsampled_length = N * upsampled_ratio;
% 创建新的时间轴
t = linspace(0, 1/(Fs), N); % 假设原始信号的频率 Fs=1 (单位:Hz)
new_t = linspace(0, 1/(Fs*upsampled_ratio), upsampled_length);
% 使用线性插值进行升采样
upsampled_signal = interp1(t, x, new_t, 'linear');
end
```
**降采样 (Downsampling):**
```matlab
function downsampled_signal = down_sampling(x, ratio, mode)
% 输入:原始信号x,降采样的比率ratio,滤波模式mode可以选择'average'或'nearest'
N = length(x);
downsampled_ratio = ratio;
if mod(N, downsampled_ratio) == 0
downsampled_length = floor(N/downsampled_ratio);
else
error('Downsampling ratio must evenly divide the signal length.');
end
% 选择降采样方式(平均法或最近邻法)
if strcmp(mode, 'average')
downsampler = @(y) mean(y(round(linspace(1, N, downsampled_length))));
elseif strcmp(mode, 'nearest')
downsampler = @(y) y(round(downsampled_length*(linspace(1, 1, N)+0.5)-0.5));
else
error('Invalid downsampling method.');
end
downsampled_signal = downsampler(x);
end
```
阅读全文