MATLAB: Why the fourier series coefficient answer in matlab different compare to the manually calculation

fourier series coefficient

i was use matlab to slove the fourier coefficient, why the answer come out different compare to my manually caculation(1/pi)*((-cos(0)/n)+(cos(n*-pi)/n^2)+(cos(n*pi)/n^2)-(cos(0)/n^2)).
sin pi*n should be get zero right?
syms n t pi
f1=(-t)
f2=(t)
a0=(1/(2*pi))*(int(f1,t,-pi,0)+int(f2,t,0,pi))
an1=int(f1*cos(n*t),t,-pi,0);
a1=subs(an1,sin(n*pi),0);
an2=int(f2*cos(n*t),t,0,pi);
a2=subs(an2,sin(n*pi),0);
an=(1/pi)*((an1+an2))
-(2*(2*sin((pi*n)/2)^2 – n*pi*sin(pi*n)))/(n^2*pi) (matlab answer)

Best Answer

As pointed by John in his comment. You need to specify that the symbolic variable n is integer explicitly. You assume() to inform MATLAB that n is an integer and then use simplify() to apply the assumption. Also, don't directly define pi as a symbolic variable. pi is built-in constant.
syms n t
PI = sym(pi);
f1=(-t);
f2=(t);
a0=(1/(2*PI))*(int(f1,t,-PI,0)+int(f2,t,0,PI));
an1=int(f1*cos(n*t),t,-PI,0);
a1=subs(an1,sin(n*PI),0);
an2=int(f2*cos(n*t),t,0,PI);
a2=subs(an2,sin(n*PI),0);
an = (1/PI)*((an1+an2));
assume(n/2, 'integer');
simplify(an)
assume((n+1)/2, 'integer');
simplify(an)
Result
ans =
0
ans =
-4/(n^2*pi)
Related Question