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

• Jan 3rd 2012, 10:12 AM
alexmahone
Plotting Fourier series approximation for a square wave using MATLAB.
Suppose $\displaystyle f(x)$ is a square wave of period $\displaystyle 2\pi$ such that

$\displaystyle f(x)=1$ for $\displaystyle 0<x<\pi$

$\displaystyle f(x)=-1$ for $\displaystyle \pi<x<2\pi$

The Fourier series for $\displaystyle f(x)$ is

$\displaystyle 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?
• Jan 3rd 2012, 10:47 AM
ILikeSerena
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;
• Jan 3rd 2012, 10:53 AM
alexmahone
Re: Plotting Fourier series approximation for a square wave using MATLAB.
Quote:

Originally Posted by ILikeSerena
Hi alexmahone! :)

Perhaps you should write

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