我认为这可能是finddelay 中的一个潜在错误。请注意此文档摘录(重点是我的):
X 和 Y 不必是彼此的精确延迟副本,因为 finddelay(X,Y) 通过互相关返回延迟的估计值。然而,这个估计的延迟只有在X 和Y 的延迟版本之间存在足够的相关性时才有意义。 另外,如果可能有多个延迟,如周期信号,则返回绝对值最小的延迟。 如果具有相同绝对值的正延迟和负延迟都是可能,返回正延迟。
这似乎暗示finddelay(y, x) 应该返回2,而实际上它返回-4。
编辑:
这似乎是与xcorr 引入的floating-point errors 相关的问题,正如我所描述的in my answer to this related question。如果您在命令行窗口中键入type finddelay,您可以看到finddelay 在内部使用xcorr。即使xcorr 的输入是整数值,结果(您也希望是整数值)最终可能会出现浮点错误,导致它们略大于或小于整数值。然后,这可以更改最大值所在的索引。解决方案是当您知道您的输入都是整数值时,对来自 xcorr 的输出进行四舍五入。
对于整数值,finddelay 的更好实现可能是这样的,它实际上会返回具有最小绝对值的延迟:
function delay = finddelay_int(x, y)
[d, lags] = xcorr(x, y);
d = round(d);
lags = -lags(d == max(d));
[~, index] = min(abs(lags));
delay = lags(index);
end
然而,在您的问题中,您要求返回正延迟,这不一定是绝对值的最小值。这是finddelay 的另一种实现,它对整数值正确工作并且优先考虑正延迟:
function delay = finddelay_pos(x, y)
[d, lags] = xcorr(x, y);
d = round(d);
lags = -lags(d == max(d));
index = (lags <= 0);
if all(index)
delay = lags(1);
else
delay = lags(find(index, 1)-1);
end
end
以下是您的测试用例的各种结果:
>> x = [0 0 1 2 2 2 0 0 0 0];
>> y = [1 2 2 2 0 0 1 2 2 2];
>> [finddelay(x, y) finddelay(y, x)] % The default behavior, which fails to find
% the delays with smallest absolute value
ans =
4 -4
>> [finddelay_int(x, y) finddelay_int(y, x)] % Correctly finds the delays with the
% smallest absolute value
ans =
-2 2
>> [finddelay_pos(x, y) finddelay_pos(y, x)] % Finds the smallest positive delays
ans =
4 2