# Math Help - Plotting Fourier series approximation for a square wave using MATLAB.

1. ## Plotting Fourier series approximation for a square wave using MATLAB.

Suppose $f(x)$ is a square wave of period $2\pi$ such that

$f(x)=1$ for $0

$f(x)=-1$ for $\pi

The Fourier series for $f(x)$ is

$f(x)=\frac{4}{\pi}\left[\frac{\sin x}{1}+\frac{\sin 3x}{3}+\frac{\sin 5x}{5}+\ldots\right]$

I tried plotting this using MATLAB (using the first 10 terms):

Code:
x=linspace(-4*pi,4*pi,100);
y=0;
k=1;
for n=1:10
y=y+4*sin(k*x)/pi*k;
k=k+2;
end
plot(x,y)
axis([-4*pi 4*pi -2 2])
xlabel('x')
ylabel('Square wave approximation using first 10 terms')
I have attached my output but it doesn't look anything like a square wave. What am I doing wrong?

2. ## Re: Plotting Fourier series approximation for a square wave using MATLAB.

Hi alexmahone!

Perhaps you should write

y=y+4*sin(k*x)/(pi*k);

y=y+4*sin(k*x)/pi*k;

3. ## Re: Plotting Fourier series approximation for a square wave using MATLAB.

Originally Posted by ILikeSerena
Hi alexmahone!

Perhaps you should write

y=y+4*sin(k*x)/(pi*k);