# How can i get the fourier series of any given function

2 views (last 30 days)
Murloc50 on 25 Nov 2021
Commented: Friedel Hartmann on 27 Nov 2021
Since there is no direct way of finding/computing the fourier seris of a function, e.g. cos(x), how would I do this?

Friedel Hartmann on 26 Nov 2021
clear
syms x f(x) k fh(x) p(x) ph(x) % a0 = a0 Formel /2
iTerme = 8;
sco = zeros(1,iTerme);
cco = zeros(1,iTerme);
% T = 2*pi, omega = 1
f(x) = piecewise(x <= pi/4, -1/(2*pi) * x, pi/4 < x,-1/(2*pi) * x + 1); % Function
for k=1:iTerme
sco(k) = 1/pi * int(sin(k * x) * (f(x)),[0,2*pi]); % coefficients
cco(k) = 1/pi * int(cos(k * x) * (f(x)),[0,2*pi]);
end
cnum = 1:iTerme; % Table with coefficients
Tabelle.num = cnum';
Tabelle.scof = sco';
Tabelle.ccof = cco';
T = struct2table(Tabelle)
T = 8×3 table
num scof ccof ___ __________ _________ 1 0.22508 -0.22508 2 9.8393e-18 -0.15915 3 -0.075026 -0.075026 4 -0.079577 0 5 -0.045016 0.045016 6 3.2798e-18 0.053052 7 0.032154 0.032154 8 0.039789 0
fplot(f(x),[0,2*pi]), title('Original'), yline(0);
figure
a0G = vpa(1/2 * 2/(2*pi) * int(f(x),[0,2*pi]),3)
a0G =
0.375
fh(x) = 1/(2*pi) * int(f(x),[0,2*pi]); % 'Mittelwert' 1. Term ist a0
for k = 1:iTerme
fh(x) = fh(x) + sco(k) * sin(k * x) + cco(k) * cos(k * x);
end
fplot(fh(x),[0,2*pi]), title('Fourier series'), yline(0);
vpa(fh(0),3)
ans =
0.046
p(x) = x/(2*pi); % 2nd Function
for k=1:iTerme
sco(k) = 1/pi * int(sin(k * x) * (p(x)),[0,2*pi]);
cco(k) = 1/pi * int(cos(k * x) * (p(x)),[0,2*pi]);
end
cnum = 1:iTerme;
Tabelle.num = cnum';
Tabelle.scof = sco';
Tabelle.ccof = cco';
T = struct2table(Tabelle)
T = 8×3 table
num scof ccof ___ _________ ____ 1 -0.31831 0 2 -0.15915 0 3 -0.1061 0 4 -0.079577 0 5 -0.063662 0 6 -0.053052 0 7 -0.045473 0 8 -0.039789 0
fplot(p(x),[0,2*pi]), title('Original'), yline(0);
figure
a0L = vpa(1/2 * 2/(2*pi) * int(p(x),[0,2*pi]),3)
a0L =
0.5
ph(x) = 1/pi * int(p(x),[0,2*pi]) * 1/(2); % 'Mittelwert' 1. Term ist a0/2
for k = 1:iTerme
ph(x) = ph(x) + sco(k) * sin(k * x) + cco(k) * cos(k * x);
end
fplot(ph(x),[0,2*pi]), title('Fourier series'), yline(0);
Friedel Hartmann on 27 Nov 2021
The series starts with a constant term, the average value, called 'Mittelwert' The routine first calculates the average value, assigns this number to ph(x) and then begins the loop for k = 1:iTerme etc. and adds the following sin and cos functions.

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!