Plot first terms of Fourier series and amplitude
2 次查看(过去 30 天)
显示 更早的评论
Hello, how can I plot the first k terms of a Fourier series on the same graph (without showing the Gibb's effect). I would also like to plot the amplitude of those terms over frequency. I want the graphs on the attached picture. How can I make them with Matlab? Thanks in advance
0 个评论
回答(1 个)
Gautam
2025-2-7
Hello Niemand83,
If you just want to plot the sine terms with the coefficients, as in the image you attached, plot the terms inside a for loop with the command "hold on". You can make another axis in the same figure using the "subplot" for plotting the magnitude of the coefficients. Here's the code that plots the coefficient magnitudes and the sine terms
% Define the period and the range for x
T = 1; % Period of the periodic function
x = linspace(0, T, 1000); % Range of x values
% Define the given function
f = @(x) ((-1/2)*(pi+x).*(x >= -pi & x <0) + (1/2)*(pi-x).*(x>=0 & x<=pi));
% Number of terms in the Fourier series
N = 50;
% Calculate the Fourier series coefficients (an and bn)
a0 = (1/T) * integral(@(x) f(x), 0, T);
an = zeros(1, N);
bn = zeros(1, N);
for n = 1:N
an(n) = (1/T) * integral(@(x) f(x).*cos(n*pi*x/2), 0, T);
bn(n) = (1/T) * integral(@(x) f(x).*sin(n*pi*x/2), 0, T);
end
% Create the Fourier series approximation
F = a0/2;
for n = 1:N
F = F + an(n) * cos(n*pi*x/2) + bn(n) * sin(n*pi*x/2);
end
% Plot the first k coefficient magnitudes and the sine terms
subplot(1,2,1)
for k=1:4
hold on
stem(k, abs(bn(k)));
end
hold off
subplot(1,2,2)
for k=1:4
hold on
plot(bn(k)*sin(2*pi*k*x))
end
hold off
You can further format the code to add labels to the plots
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!