Plotting a Fourier series using Matlab

$\begingroup$

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.

$\endgroup$

3 Answers

$\begingroup$

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)'); 
$\endgroup$1$\begingroup$

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.

$\endgroup$0$\begingroup$

You can create a function of the amplitude and frequency of the term inside the summation, depending only on n - the dummy variable.

Using the values you provided, you have:

A = 10; T = 2; w0 = 2*pi/T; N = 10; 

Now, the amplitude and frequency as function of the iterator n is:

a = @(n) 1./(2*n-1); % amplitude w = @(n) (2*n-1)*w0; % frequency 

Now, the (truncated) Fourier series may be give as:

xt = @(t,n) 4*A/pi*sum(a(1:n).*sin(w(1:n)*t)); % fourier series 

This is a function of the number of terms n you want to include in your approximation of the infinite series and the also a number of the independent variable t.

If you want to create a plot of the function, you must create the independent variable array and the dependent variable array.

t = -2*T:T/100:T*2; % plots from -2T to 2T, with a step of T/100 x = 0*t; % pre-allocate for speed for i=1:length(t) x(i) = xt(t(i),N); % calculates the value for each t(i) in the array t end figure plot(t,x) 

This code does not use any function from the symbolic toolbox that may not be available depending on your version of MATLAB.

$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like