![]() |
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的格式表示抱歉。 [B]回答:[/B] 除了没有定义x ,而且变量x1 , x2 , buffer和answer都为零外,我不确定为什么要像这样设置嵌套循环。我不知道为什么您需要以这种方式重现[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/conv.html"]CONV[/URL]的行为,但是这是我设置嵌套的for循环解决方案的方法: X = [1 2 1]; Y = [3 1 1]; nX = length(X); nY = length(Y); nOutput = nX+nY-1; output = zeros(1,nOutput); for indexY = 1:nY for indexX = 1:nX indexOutput = indexY+indexX-1; output(indexOutput) = output(indexOutput) + X(indexX)*Y(indexY); end end 但是,由于这[I]是[/I] MATLAB,因此有矢量化这种循环的替代方法。下面是一个这样的解决方案,它使用函数[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sum.html"]SUM[/URL] , [URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/spdiags.html"]SPDIAGS[/URL]和[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/flipud.html"]FLIPUD[/URL] : output = sum(spdiags(flipud(X(:))*Y)); [url=https://stackoverflow.com/questions/3525876]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 14:17。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.