Plot Fourier Series on MatLab

Trying to plot the first few terms of my fourier series function but I cant seem to resemble the original function for n values greater than two.
n=[2:2:12]; % define n as only even numbers
for f=1:length(n) % define f
for Time=1:length(t)
a_not=1/pi;
b_n=(1/2)*sin((pi*t(Time))/T);
fourier(Time)=a_not+b_n+sum((2/(pi*(1-n(f)^2)))*cos((n(f)*pi*t(Time))/T));
end
figure(2)
plot(t,fourier,t,y)
hold on
end

Réponses (1)

Asvin Kumar
Asvin Kumar le 10 Avr 2020

0 votes

Your coefficients are right. The issue is that instead of adding the n-th cosine to the exiting variable ‘fourier’, you were overwriting it. Here’s a simpler, stripped down and vectorized version of your code:
n=2:2:12; % define n as only even numbers
a_not=2/pi;
b1 = 0.5;
fourier = a_not/2*ones(size(t)) +b1*sin(pi*t/T) ;
for f=1:length(n) % define f
fourier = fourier + 2 / (pi*(1-n(f)^2)) * cos(n(f)*pi*t/T);
end
plot(t,fourier)
If you’re looking for a simpler way to do this have a look at the example at https://www.mathworks.com/help/curvefit/fourier.html#FitFourierModelsExample-1

Catégories

En savoir plus sur MATLAB dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by