# MATLAB Plotting Fourier series coefficients

• Jan 25th 2009, 10:47 AM
synnexster
MATLAB Plotting Fourier series coefficients
http://i40.tinypic.com/20k61sm.jpg

I'm trying to plot the above fourier series coefficients, what am I doing wrong? here is my matlab code:

Code:

```clear time=-1:0.01:1; l=0.5; x=0; %initialize to 0 for n=1:40 if (n==2*l), x=x-(1/(pi*l)); end;  if (n==(2*l+1)), x=x+(2/((pi*(2*l+1))))*(1+(2*(-1)^l)/(pi*(2*l+1))); end; plot(time,real(x)) xlabel('time (sec)') ylabel('x(t)') title(['n=', int2str(n), ' Fourier Series Approximation']) pause(1) end```
• Jan 25th 2009, 12:29 PM
Constatine11
Quote:

Originally Posted by synnexster
http://i40.tinypic.com/20k61sm.jpg

I'm trying to plot the above fourier series coefficients, what am I doing wrong? here is my matlab code:

Code:

```clear time=-1:0.01:1; l=0.5;   x=0; %initialize to 0   for n=1:40   if (n==2*l), x=x-(1/(pi*l)); end;    if (n==(2*l+1))     x=x+(2/((pi*(2*l+1))))*(1+(2*(-1)^l)/(pi*(2*l+1)));   end;   plot(time,real(x))   xlabel('time (sec)')   ylabel('x(t)')   title(['n=', int2str(n), ' Fourier Series Approximation'])   pause(1) end```

1. Don't use l as a variable name, it is too easy to confuse it with 1.

2. l is a constant, so the loop only does anything when n=1, and n=2.

3. It looks as though you intend x to be an array, but its only a scalar.

4. It is not clear what you are trying to do here.

The following creates an array of the coefficients:

Code:

```clear   b=zeros(1,40); %initialize to a row vector of 40 0's   for n=1:40   if (mod(n,2)==0)     L=n/2;     b(n)= -1/(pi*L);   else     L=(n+1)/2;     b(n)=2/((pi*(2*L+1))))*(1+(2*(-1)^L)/(pi*(2*L+1));   end end```
.