In: Advanced Math
solve any question about fourier series by using MATLAB
this is an example how to plot fourier series in MATLAB.
clear variables
close all
% Fourier series of neither even nor odd function
% Decompose f(x) into even (fe) and odd (fo) functions.
% fe = (f(x) + f(-x))/2, fo = (f(x) - f(-x))/2
N = 500;
L = 4;
xd = -L:2*L/(N-1):L;
y1 = -1/8*xd.^2;
y2 = 1/8*xd.^2;
fo = y1.*(-L<=xd & xd<=0) +y2.*(0<=xd &
xd<=L);
fe = 4-xd.^2/8;
f2 = fe + fo;
a0 = 10/3;
% Generate the fourier series of f(x)
y = zeros(1,N);
x = [];
K = 80;
for k = 1:K
ck = 1/(pi*k);
an = (2*L*(-1).^(k+1))*ck^2;
bn = L*(-1).^(k+1)*ck + (2*L*ck^3)*((-1)^k-1);
y = y + (an*cos(pi*k/L*xd)+ bn*sin(pi*k/L*xd)); % For fe and
fo
x = [x;y];
end
y = a0 +y;
x = a0 +x;
% Color codes
s = distinguishable_colors(K); % search this function on
mathworks
figure
subplot(121) % Plot f(t)
plot(xd,f2,'linewidth',2.5,'color',s(1,:))
line(xlim,[0 0],'color',s(6,:),'linewidth',3);
line([0 0],ylim,'color',s(6,:)','linewidth',3);
ylim([-.5 4]);
a= xlabel('\itt\rm (seconds)');
set(a,'fontsize',20);
a = ylabel('\itf\rm(\itt\rm)');
set(a,'fontsize',20);
a= title('f(t)');
set(a,'fontsize',14);
grid
subplot(122) % Plot fouries series of f(t);
hold on
q = length(x(:,1));
M = 1:q;
for i = 1:6:q
plot(xd,x(i,:),'linewidth',2.5,'color',s(i,:),'DisplayName',sprintf('S
= %1.2f',M(i)))
end
a= title('Fourier series of f(t)');
set(a,'fontsize',14);
a= xlabel('\itt\rm (seconds)');
set(a,'fontsize',20);
a = ylabel('\itf\rm(\itt\rm)');
set(a,'fontsize',20);
line(xlim,[0 0],'color',s(6,:),'linewidth',3);
line([0 0],ylim,'color',s(6,:)','linewidth',3);
legend('-DynamicLegend','location','bestoutside');
grid