在matlab中编写卷积函数出现问题
嘿,我在编写与 conv(x,y)
函数等效的 matlab 时遇到了困难。我不明白为什么这会给出不正确的输出。对于数组
x1 = [1 2 1]
和 x2 = [3 1 1]
。
这就是我所得到的
x1 = [1 2 1];
x2 = [3 1 1];
x1len = leng(x1);
x2len = leng(x2);
len = x1len + x2len - 1;
x1 = zeros(1,len);
x2 = zeros(1,len);
buffer = zeros(1,len);
answer = zeros(1,len);
for n = 1:len
buffer(n) = x(n);
answer(n) = 0;
for i = 1:len
answer(n) = answer(n) + x(i) * buffer(i);
end
end
matlab conv(x1,x2)
给出 3 7 6 3 1
作为输出,但这给了我 3 5 6 6 6
代码> 寻求答案。
我哪里出错了?
另外,对于我在 Opera Mini 上的格式感到抱歉。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了没有定义
x
以及变量x1
、x2
、buffer
和 < code>answer,我不确定为什么你要像这样设置嵌套循环。我不知道为什么您需要重现 CONV 的行为 这样,但我将如何设置嵌套 for 循环解决方案:但是,由于这是 MATLAB,因此有矢量化的替代方案可以替代这种方式的循环。一种这样的解决方案如下,它使用函数 SUM、SPDIAGS 和 FLIPUD:
Aside from not having
x
defined, and having all zeroes for your variablesx1
,x2
,buffer
, andanswer
, I'm not certain why you have your nested loops set up like they are. I don't know why you need to reproduce the behavior of CONV this way, but here's how I would set up a nested for-loop solution:However, since this is MATLAB, there are vectorized alternatives to looping in this way. One such solution is the following, which uses the functions SUM, SPDIAGS, and FLIPUD:
在给定的代码中,所有向量在开始之前都被清零,除了从未定义的
x
。所以很难准确地看出你在说什么。但有几点需要注意:for
循环中,您使用的buffer
值尚未由外部循环设置。1:len
,而不是相对于另一个向量移动一个向量。您可能还想考虑“向量化”其中一些,而不是嵌套
for
循环——例如,您的内部循环只是计算点积,而对于该点积,已经存在一个完美的 Matlab 函数。(当然,对于
conv
也可以这样说——但我猜你是在重新实现它,或者作为家庭作业,或者了解它是如何工作的?)In the code as given, all vectors are zeroed out before you start, except for
x
which is never defined. So it's hard to see exactly what you're getting at. But a couple of things to note:for
loop you are using values ofbuffer
which have not yet been set by your outer loop.1:len
rather than shifting one vector relative to the other.You might also want to think about "vectorizing" some of this rather than nesting
for
loops -- eg, your inner loop is just calculating a dot product, for which a perfectly good Matlab function already exists.(Of course the same can be said for
conv
-- but I guess you're reimplementing either as homework or to understand how it works?)