简体   繁体   中英

Fourier series graph generation from given coefficients an, bn in Matlab(Scilab)

I've calculated coefficients an, bn (100, T=2*pi) in c++ and checked that they are correct using few sources. Now i try to generate Fourier series graph for given example function in Scilab :

(x+2)*abs(cos(2*x*(x-pi/6)))

M=csvRead(filename, ";", [], 'double') 
n=size(M,1)

for i = 1:n
    A(i)=M(i)
    B(i)=M(i + n)
end

function series=solution(x) 
    series=A(1)/2;
    for i = 2:n
        series=series+(A(i)*cos(i*x)+B(i)*sin(i*x));
    end
endfunction

function series=solution2(x)
    series=(x+2).*abs(cos(2.*x.*(x-%pi/6)));
endfunction

x = -%pi:%pi/100:%pi
plot2d(x, solution(x), 3)

x2 = -%pi:%pi/100:%pi 
plot2d(x2, solution2(x2), 4)

Here is the result:

在此处输入图片说明

It clearly looks that tendency is ok but the beginning and the end of the period are wrong (reversed?). Do you see any issues in Scilab code? What could cause the problem - values in sin/cos in function solution(x)? Should i provide an, bn values and check for miscalculation there?

I don't know how did you calculated your A & B coefficients, but I assume that you used the usual notations to get the first line of the below formula:

方程

Thus n starts from 1. Since Scilab starts vector indexing from 1, you correctly made your loop from 2, but forgot to compensate for this "offset". Your function should be something like this:

function series=solution(x) 
    series=A(1)/2;
    for i = 2:n
        series=series+(A(i)*cos((i-1)*x)+B(i)*sin((i-1)*x));
    end
endfunction

Since you didn't provided A & B , I can not check the result.

Additional note: Syntactically more correct if you explicitly define all input variables in a function, like this:

function series=solution(x,A,B)

This way you may be sure that your input is not changed somewhere else in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM