clear;
clc;

fprintf('Fouriercomponenten of a triangle wave\n\n');

B = input('Amplitude B of the triangle wave [V]: ');
T = input('Period T of the triangle wave [ms]: ');
fprintf('\n');

w0 = 2*pi/T;
amp = -(8*B)/(pi^2);

tv = 0:T/50:2*T;

ehv = amp*cos(w0*tv);
dhv = (amp/9)*cos(3*w0*tv);
vhv = (amp/25)*cos(5*w0*tv);

rc = 4*B/T;
T2 = T/2;
T15 = 3*T/2;

drv=[];
for t=0:T/50:2*T;
    if (t<T/2)        drv=[drv -B+rc*t];   end;
    if (T/2<=t)&(t<T) drv=[drv 3*B-rc*t];  end;
    if (T<=t)&(t<T15) drv=[drv -5*B+rc*t]; end;
    if (T15<=t)       drv=[drv 7*B-rc*t];  end;
end;

epdhv = ehv + dhv;
epdpvhv = epdhv + vhv;

figure(1);
set(clf,'PaperType','A4');
set(clf,'Color',[1,1,1]);
subplot(221);
plot(tv, drv, tv, ehv, tv, dhv, tv, vhv);
xlabel('time [ms]','Fontsize',8);
title('first three harmonics','Fontsize',8);
set(gca,'Fontsize',8);

subplot(222);
plot(tv, drv, tv, ehv);
xlabel('time [ms]','Fontsize',8);
title('first harmonic','Fontsize',8);
set(gca,'Fontsize',8);

subplot(223);
plot(tv, drv, tv, epdhv); 
xlabel('time [ms]','Fontsize',8);
title('sum first and third harmonic','Fontsize',8);
set(gca,'Fontsize',8);

subplot(224);
plot(tv, drv, tv, epdpvhv);
xlabel('time [ms]','Fontsize',8);
title('sum of all harmonics','Fontsize',8);
set(gca,'Fontsize',8);
