Plotting a Fourier series using Matlab

7.3k Views Asked by At

i am trying to plot the following Fourier series $x(t)$

x(t) CLICK TO VIEW

t=0:0.01:2;
A = 10;
T = 2;
w0 = 2*pi/T;
N = 10;

xN = zeros(1,length(t)); % dc component
for n=1:N
   xN = xN + (1/(2*n-1)) * sin(2*n -1)*w0*t;
end

x = (4*A/pi) * xN;
plot(t,x)
xlabel('t')
ylabel('x(t)')

The result must be:

 this CLICK TO VIEW

My code doesn't seem to be working, any help would be much appreciated, thank you.

2

There are 2 best solutions below

1
On

You can always use the symbolic toolbox - I find it nicer for doing things such as computing Fourier Series. Example code below.

syms t n k

A = 10;
w_0 = pi;

%% Formula for the Fourier Series

fourierseries = @(t,k) 4*A/pi*symsum(sin((2*n-1)*pi*t)/(2*n-1),n,1,k);

%% Plot with 20 Fourier coefficients

ezplot(fourierseries(t,20),-2,4)
title('Fourier Series'), xlabel('t'), ylabel('f(x)');
0
On

Your brackets are wrong. Correct would be (note the added brackets after sin)

for n=1:N
  xN = xN + (1/(2*n-1)) * sin( (2*n -1)*w0*t );
end

The code the way you wrote it is interpreted differently. In your code the argument of the sine function is only (2*n-1), which is a constant.