Implementation of Fourier Series up to ‘n’ Harmonics in MATLAB
Last Updated :
28 Apr, 2022
In Mathematical Calculus, the expanded form of a periodic function “f(x)” in terms of an infinite sum of cosines & sines is called as Fourier series. It makes use of the orthogonality relationships of the cosine & sine functions. In other words, the Fourier series can also be defined as a way of representing any periodic function “f(x)” as a sum of cosine and sine functions (possibly infinite).
For a periodic function “f(x)”, the Fourier series of “f(x)” in the Range of [ c, c+2l ] is given by :
(In General, l=Ï€)
Here:
Here, an & bn are called Fourier cosine and sine coefficients respectively.
Note: If in the above formula of Fourier Series, instead of Infinity we use summation from n=1 to n=k then we call it as Fourier series of f(x) up to ‘k’ harmonics.
MATLAB functions used in the code are:
- disp(“txt”): This Method displays the Message-“txt” to the User.
- input(“txt”): This Method displays the Message-“txt” and waits for the user to input a value and press the Return key.
- int(y,x1,x2): This Method computes the definite integral of ‘y’ from x1 to x2.
- vpa(f,4): This Method evaluates each element of ‘f’ to at least 4-Significant digits.
- ezplot(y,[x1,x2]): This Method plots ‘y’ over the specified interval [x1,x2].
- title(‘GFG’): This method adds the specified title-“GFG” to a plot.
- legend(A,B,…): This Method creates a legend with descriptive labels for each plotted line.
- strcat(A,B): This Method horizontally concatenates the text in its input arguments.
- char(f): This Method converts the input array ‘f’ to a character array.
Example:
Matlab
clear all
clc
disp("Implementation of Fourier Series
up to 'n' Harmonics in MATLAB | GeeksforGeeks")
syms x
f=input( "Enter the function of x, whose fourier series is to be found:" );
I=input( "Enter the limits of Integration [a , b] :" );
k=input( "Enter the number of Harmonics:" );
a=I(1);
b=I(2);
l=(b-a)/2;
a0=(1/l)*(int(f,a,b));
Fx=a0/2;
for n=1:k
figure;
an(n)=(1/l)*(int(f*cos(n*pi*x/l),a,b));
bn(n)=(1/l)*(int(f*sin(n*pi*x/l),a,b));
Fx=Fx+((an(n))*cos(n*pi*x/l))+((bn(n))*sin(n*pi*x/l));
Fx=vpa(Fx,4);
ezplot(Fx,[a,b]);
hold on;
ezplot(f,[a,b]);
title([ "The Fourier series upto " , num2str(n), " Harmonics is:" ]);
legend( "Fourier series" , "Given Function" );
hold off;
end
disp(strcat( 'The Fourier series upto ' , num2str(n), ' Harmonics is:' ,char(Fx)))
|
Output:
Input: For a function in the Range= [ -π, π ],
Fourier Series of f(x) up to '3' Harmonics is:
Input: For a function f(x)=e-x in the Range= [ 0, 2Ï€ ],
Fourier Series of f(x) up to '4' Harmonics is:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...