Skip to content

Instantly share code, notes, and snippets.

@KuanYuChang
Last active March 30, 2018 05:00
Show Gist options
  • Select an option

  • Save KuanYuChang/ef6171b4117dc5924af93b134f78c0e3 to your computer and use it in GitHub Desktop.

Select an option

Save KuanYuChang/ef6171b4117dc5924af93b134f78c0e3 to your computer and use it in GitHub Desktop.
Demo of the Fourier Series
%% Remove items from workspace
clear;
%% Interval of x
x = linspace(-10, 10, 10000);
%% Example 1
orig = x;
a_0 = 0;
a_k = @(k) 0;
b_k = @(k) (-1)^(k + 1) * 2 / k;
%% Example 2
% orig = pi .* (x <= 0) + 2 .* x .* (x > 0);
% a_0 = pi;
% a_k = @(k) 2 * ((-1)^k - 1) / (pi * k^2);
% b_k = @(k) (-1 - (-1)^k) / k;
%% Degree of trigonometric polynomial
% k = 1;
% k = 5;
% k = 10;
% k = 100;
k = 1000;
%% Main function
appx_degree = @(k, x) a_k(k) * cos(k * x) + b_k(k) * sin(k * x);
appx = ones(size(x)) * a_0;
for i = 1:k
appx = appx + appx_degree(i, x);
end
%% Set x-axis limits
xlim([-pi pi]);
% xlim([(-2 * pi) (2 * pi)]);
% xlim([(-3 * pi) (3 * pi)]);
%% Plotting section
hold on;
grid on;
plot(x, orig, x, appx);
lgnd = ["origin" ("approx. n = " + int2str(k))];
legend(lgnd);
hold off;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment