将for循环从matlab转移到c ++

时间:2014-04-13 18:20:33

标签: c++ matlab for-loop

我在matlab中写了这个for循环:

b1=zeros(size(raw));
a1=zeros(size(raw));
filtered = zeros(size(raw));

raw=ones(124,1);
[b,a]=butter(4,6/64,'high');

for n = 5:124

    b1(n)=(b(1)* raw(n))   + (b(2)* raw(n-1) )+ (b(3)* raw(n-2))+ (b(4)* raw(n-3) );
    a1(n)=(b(5)* raw(n-4))-    (a(2)*filtered(n-1)) - (a(3)*filtered(n-2))-(a(4)*filtered(n-3) )- (a(5)*filtered(n-4));

    filtered(n)=b1(n)+a1(n);
end

这在c ++中

for(int i=0;i<124;i++)
{
    temp[i]=1;
}
long double f_temp[124]={0};

long double a[5]={1.0000,-3.2317,3.9766,-2.2014,0.4617};    
long double b[5]={ 0.6795,-2.7178,4.0768,-2.7178,0.6795};

for(int n=4;n<124;n++)
{
    b1=(b[0]*temp[n])+(b[1]*temp[n-1])+(b[2]*temp[n-2]) +(b[3]*temp[n-3]);
    a1=(b[4]*temp[n-4])-(a[1]*f_temp[n-1])-(a[2]*f_temp[n-2])-(a[3]*f_temp[n-3])-(a[4]*f_temp[n-4]);

    f_temp[n]=b1+a1;
}

任何人都可以解释为什么他们不给出相同的答案?输入相同,输出数组在两种情况下都初始化为零。

1 个答案:

答案 0 :(得分:1)

您使用ab的错误常量值,两个变量都已交换。

调试您的m代码:

a=[ 0.67945921749947324475016330325161, -2.7178368699978929790006532130064, 4.076755304996839690545584744541, -2.7178368699978929790006532130064, 0.67945921749947324475016330325161]

b=[ 1.0, -3.2316755470122213722561355098151, 3.9766405223795340262427089328412, -2.2013664741369440847051919263322, 0.46166493646287282137663510184211]