如何修复Octave中绘图时的向量尺寸不匹配错误?
解决Octave中conv函数输出与时间轴长度不匹配的绘图错误
问题场景
在Octave中编写线性控制系统代码时,生成输入信号x后通过conv函数计算系统输出y,发现时间向量t长度为151,而y长度为155,调用plot(t,y)时触发向量长度不匹配的错误。
原代码
%Linear Control system %1: input signal, x(t) will be sampled 150 times at twice the nyquist rate %2: x(t) = 2*cos(2*pi*t) + 5*cos(10*pi*t) + 3*cos(15*pi*t); clear; clc; n = 0:150; Ts = 1/30; t = n.*Ts; x = 2.*cos(2.*pi.*t) + 5.*cos(10.*pi.*t) + 3.*cos(15.*pi.*t); fc = 2; negM = -2; posM = 2; k = negM:posM; a = (sin((2.*pi.*fc.*k)./ 30)./(k.*pi)); a(3) = 2.*( fc./ 30); b = 0.54 +0.46.*cos((k.*pi)./posM); h = a.*b; y = conv(h,x); size(t) size(y) plot(t,x); %plot(t,y)
尺寸输出与错误信息
- 尺寸输出:
t长度为151,y长度为155 - 错误信息:
error: __plt2vv__: vector lengths must match error: called from __plt__>__plt2vv__ at line 489 column 5 __plt__>__plt2__ at line 248 column 14 __plt__ at line 115 column 16 plot at line 235 column 10 Projects name* at line 30 column 1
问题原因
卷积运算的输出长度遵循公式:length(y) = length(x) + length(h) - 1。这里输入信号x长度为151,系统冲激响应h长度为5(k从-2到2共5个元素),因此y的长度为151+5-1=155,与原时间向量t长度不匹配,导致绘图触发错误。
修正方法
方法1:生成匹配卷积输出的时间向量
卷积后的信号时间范围需要扩展:起点为原时间起点加上冲激响应最左侧索引对应的时间偏移,终点为原时间终点加上冲激响应最右侧索引对应的时间偏移。修改代码如下:
% 生成匹配y长度的时间向量 t_y = t(1) + negM*Ts : Ts : t(end) + posM*Ts; % 绘图 plot(t_y, y);
方法2:使用卷积的same参数截取中间结果
调用conv时添加第三个参数'same',直接返回与输入信号x长度相同的卷积结果(取中间部分),无需修改时间向量即可绘图:
% 生成与x长度相同的卷积结果 y = conv(h, x, 'same'); % 直接用原t绘图 plot(t, y);
内容的提问来源于stack exchange,提问作者whyyouneed toknow
相关产品推荐
相关产品推荐

