How do I plot this Fourier series funcion?
Show older comments
Hello everyone,
I have tried to plot the function below from (0,pi) for a0 and the first six terms of the series on matlab. I did not know how to include the sin and cos function together so I tried to plot the cos term first, However, it seems like it does not work with the followig code becaue of (cos, sin) error. I would appriciate your help.
a0 = pi/4
an = 1/pi(cos(n*pi)-1)
bn = (-1*cos(n*pi))/n
f(t) = a0 + sum(an*cos(n*t))+ sum(bn*sin(n*t))
t = 0:0.1:2*pi;
n = 6;
ycos = cos(t,n);
plot(x,ycos),grid
xlabel('t'),ylabel('cos function')
% Define functions
function f = fcos(t,n)
f = zeros(1,numel(t));
f = pi/4;
for i = 1:n
an = -1/pi(cos(i*pi)-1) ;
f = f + an*cos(i*t);
end
Answers (1)
I am not exactly certain what you want to do, however the loop is likely not necessary, sinc it is prefgerable to use MATLAB’s vectorisation capabilities —
t = 0:0.1:2*pi;
n = 1E-8+(0:6).'; % Adding 1E-8 Prevents NaN Values In The Output, Transposed To Column Vector
a0 = pi/4;
an = 1./(pi*(cos(n*pi)-1))
bn = (-1*cos(n*pi))./n
f = @(t) a0 + sum(an.*cos(n.*t))+ sum(bn.*sin(n.*t));
figure
plot(t, f(t))
grid
Make appropriate changes to get different results.
.
6 Comments
Hasan Al Tarify
on 8 Oct 2021
Edited: Hasan Al Tarify
on 8 Oct 2021
I do not exactly understand.
The resolution of the square waves can be increased by increasing ‘n’ and ‘t’ —
% t = 0:0.1:2*pi;
t = linspace(0, 6*pi, 500);
n = 1E-8+(0:16).'; % Adding 1E-8 Prevents NaN Values In The Output, Transposed To Column Vector
a0 = pi/4;
an = 1./(pi*(cos(n*pi)-1))
bn = (-1*cos(n*pi))./n
f = @(t) a0 + sum(an.*cos(n.*t))+ sum(bn.*sin(n.*t));
figure
plot(t, f(t))
grid
Since a square wave pulse train is the sum of the scaled odd multiples of a sine curve, one way to create it is simply —
t = linspace(0, 2, 1500);
n = 1:2:16;
f = 2.5;
f = sum(sin(n(:)*2*pi*t*f)./n(:));
figure
plot(t, f)
grid
A cosine series is not necessary.
.
Hasan Al Tarify
on 8 Oct 2021
Edited: Hasan Al Tarify
on 8 Oct 2021
Star Strider
on 8 Oct 2021
They both ran without error for me. I have no idea what the problems is, since I cannot reproduce it.
The ‘t’ and ‘n’ vectors in the second plot are different from those in the first plot, so it is not possible to run both of them with the same ‘t’ and ‘n’ vectors. Run them separately (at least with the vectors created for them), and they should work correctly.
.
Hasan Al Tarify
on 8 Oct 2021
Star Strider
on 8 Oct 2021
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.
Categories
Find more on Filter Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


