Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

% 匹配器输出端信号 output = conv(r1, x); subplot(4,1,4); t31 = -1:1/2e9:0.25e-6; t32 =…

  1. User

    % 匹配器输出端信号 output = conv(r1, x_); subplot(4,1,4); t3_1 = -1:1/2e9:0.25e-6; t3_2 = 0.25e-6:1/2e9:0.5e-6; t3_3 = 0.5e-6:1/2e9:0.75e-6; t3_4 = 0.75e-6:1/2e9:1e-6; plot(t3_1, output(1:numel(t3_1))); hold on; plot(t3_2, output(numel(t3_1)+1:numel(t3_1)+numel(t3_2))); plot(t3_3, output(numel(t3_1)+numel(t3_2)+1:numel(t3_1)+numel(t3_2)+numel(t3_3))); plot(t3_4, output(numel(t3_1)+numel(t3_2)+numel(t3_3)+1:end)); title('匹配器输出端信号波形'); xlabel('时间(秒)'); ylabel('幅度');该代码报错:索引超出数组元素的数目(3043);报错语句为:plot(t3_1, output(1:numel(t3_1)));请解决

  2. Assistant

    这个错误表示 output 数组的长度为 3043,但在 plot 函数中使用的索引超过了这个长度。排查代码后发现,由于 conv 函数的结果比输入信号长度长,因此 output 数组的长度应为 N+M−1N+M-1,其中 NN 是输入信号的长度,MM 是滤波器的长度。

    解决方式是修改 output 数组的定义,让它的长度等于 N+M−1N+M-1。具体实现可以在 conv 函数之后加上下面这行代码:

    output = output(1:numel(x_)+numel(r1)-1);
    

    这行代码可以截取 output 数组的前 N+M−1N+M-1 个元素,即滤波器的输出。修改后的完整代码如下:

    % 信号发生器
    fs = 2e6; % 采样率
    Ts = 1 / fs; % 采样时间间隔
    t = 0:Ts:0.5e-6; % 时间向量
    f0 = 200e3; % 信号频率
    x = sin(2*pi*f0*t); % 正弦波信号
    
    % 比较器
    threshold = 0; % 阈值
    x_(x > threshold) = 1;
    x_(x <= threshold) = 0;
    
    % 带通滤波器
    fc1 = 150e3; % 通带下限
    fc2 = 250e3; % 通带上限
    fs_ = fs / 2; % 实际采样率
    order = 50; % 滤波器阶数
    f1 = fc1 / fs_; % 数字滤波器通带下限
    f2 = fc2 / fs_; % 数字滤波器通带上限
    [b, a] = butter(order, [f1, f2], 'bandpass');
    y = filter(b, a, x_);
    
    % 匹配器
    r1 = fliplr(y); % y(n) 反转
    output = conv(r1, x_);
    output = output(1:numel(x_)+numel(r1)-1);
    
    % 绘图
    subplot(4,1,1);
    plot(t, x);
    title('原始信号波形');
    xlabel('时间(秒)');
    ylabel('幅度');
    
    subplot(4,1,2);
    plot(t, x_);
    title('比较器输出端信号波形');
    xlabel('时间(秒)');
    ylabel('幅度');
    
    subplot(4,1,3);
    plot(t, y);
    title('带通滤波器输出端信号波形');
    xlabel('时间(秒)');
    ylabel('幅度');
    
    subplot(4,1,4);
    t3_1 = -1:1/2e9:0.25e-6;
    t3_2 = 0.25e-6:1/2e9:0.5e-6;
    t3_3 = 0.5e-6:1/2e9:0.75e-6;
    t3_4 = 0.75e-6:1/2e9:1e-6;
    plot(t3_1, output(1:numel(t3_1)));
    hold on;
    plot(t3_2, output(numel(t3_1)+1:numel(t3_1)+numel(t3_2)));
    plot(t3_3, output(numel(t3_1)+numel(t3_2)+1:numel(t3_1)+numel(t3_2)+numel(t3_3)));
    plot(t3_4, output(numel(t3_1)+numel(t3_2)+numel(t3_3)+1:end));
    title('匹配器输出端信号波形');
    xlabel('时间(秒)');
    ylabel('幅度');
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.