MATLAB: Expansion in a Fourier Series

fourier series

I created a code that is supposed to calculate a0, an, bn, and f(x), for some reason it won't work when I include cos(n*pi)=(-1)^n to cos(-n*pi)=cos(n*pi). I want these three rules to apply while the code is running cause it's need to calculate an and bn correctly. Below is the code I have so far can someone please help fix this code so I calculate for all four functions.
MatLab Code Below:
% Problem_1 the Fourier series of the function f(x)
% f(x)=0 -pi < x < 0
% f(x)=1 0 < x < pi
clear all;clc;
syms x n pi
% pi=3.14;
sum=0;
y=0 %function you want
y1=1
a0=1/pi*int(y,x,-pi,0)+1/pi*int(y1,x,0,pi)
% for n=1:50
%finding the coefficients
cos(n*pi)=(-1)^n
sin(pi*n)=0
cos(-n*pi)=cos(n*pi)
an=(1/pi)*int(y*cos(n*x),x,-pi,0)+(1/pi)*int(y1*cos(n*x),x,0,pi)
bn=(1/pi)*int(y*sin(n*x),x,-pi,0)+(1/pi)*int(y1*sin(n*x),x,0,pi)
sum=sum+(an*cos(n*x)+bn*sin(n*x))
% end

Best Answer

cos(n*pi)=(-1)^n
that is an assignment statement. n is a symbolic variable. The only time that can have NAME(SYMBOLIC_EXPRESSION) on the left side of an assignment statement is if you are defining a symbolic function. So you are defining a symbolic function named cos with variable name n*pi. But that is an invalid variable name unless pi happens to equal 1.
Perhaps you want to use subs()
Related Question