%Problem 1.26 Power Electronics
%Rob Garrone 9_13_14

%initial pulse train visualization
pulsewidth = 1/100000; % pulse width
ydutycycle = .75; %75 percent duty cycle
t = 0 : 1/10e6 : 11*pulsewidth;   %1Mhz sample rate 
t2 = 0: 1/10e6: 50*pulsewidth;
d = 0 : pulsewidth : 10*pulsewidth; %100kHz pulse train for 10 cycles 
V_A = 10*pulstran(t,d,@rectpuls,(pulsewidth*ydutycycle)); %7.5us pulse, a 75% duty cycle as described
figure();
plot(t,V_A); 
hold on;
V_OUT = 10*ydutycycle;
plot(t,V_OUT,'r');
axis([0 10*pulsewidth -0.5 11]);
title('Relationship of Input and Output Voltage over 10 cycles') %Title
xlabel('Seconds'); % x-axis label
ylabel('Voltage'); % y-axis label
legend('V_A','V_O'); %Legend

%Transfer function of RLC filter circuit:
R = .5; % Resistor
C = 100e-6; %Capacitor
L = 5e-6; %Inductor

w = linspace(1000,130000,1000); %1000 points between 1kHz and 130kHz


figure();
H = tf([(R^2)*C -R] , [(R^2)*L*(C^2) 0 (R^2)*C-L -R]);
bodeplot(H,w);
title('RLC Frequency Response Bode Plot') %Title

figure();

%fourier series expansion of our signal

w_0 = 2*pi/(10e-6); % omega zero term

a_0 = 7.5; % fourier series a_0 term

%fourier series a_n terms

a_1 = (10/(1*pi))*(sin(.75*1*pi)-sin(-.75*1*pi)); 

a_2 = (10/(2*pi))*(sin(.75*2*pi)-sin(-.75*2*pi)); 

a_3 = (10/(3*pi))*(sin(.75*3*pi)-sin(-.75*3*pi)); 

a_4 = (10/(4*pi))*(sin(.75*4*pi)-sin(-.75*4*pi)); 

a_5 = (10/(5*pi))*(sin(.75*5*pi)-sin(-.75*5*pi)); 

%fourier series b_n terms

b_1 = (-10/(1*pi))*(cos(.75*1*pi)-cos(-.75*1*pi)); 

b_2 = (-10/(2*pi))*(cos(.75*2*pi)-cos(-.75*2*pi));

b_3 = (-10/(3*pi))*(cos(.75*3*pi)-cos(-.75*3*pi)); 

b_4 = (-10/(4*pi))*(cos(.75*4*pi)-cos(-.75*4*pi)); 

b_5 = (-10/(5*pi))*(cos(.75*5*pi)-cos(-.75*5*pi)); 

a_array = [a_1*cos(1*w_0), a_2*cos(2*w_0), a_3*cos(3*w_0), a_4*cos(4*w_0), a_5*cos(5*w_0)];

b_array = [b_1*sin(1*w_0), b_2*sin(2*w_0), b_3*sin(3*w_0), b_4*sin(4*w_0), b_5*sin(5*w_0)];

C_array = sqrt(a_array.^2 + b_array.^2);

theta_array = atan2(-b_array,a_array);

n= [1:5];
subplot(2,1,1); stem(n,C_array); title('Amplitude Spectra of the Harmonics');
ylabel('C_n');
xlabel('nth harmonic');
subplot(2,1,2); stem(n,theta_array); title('Phase Spectra of the Harmonics');
ylabel('\theta_n');
xlabel('nth harmonic');

figure();

a_n_component = a_1*cos(1*w_0*t) + a_2*cos(2*w_0*t) + a_3*cos(3*w_0*t) + a_4*cos(4*w_0*t) + a_5*cos(5*w_0*t);

b_n_component =  b_1*sin(1*w_0*t) + b_2*sin(2*w_0*t) + b_3*sin(3*w_0*t) + b_4*sin(4*w_0*t) + b_5*sin(5*w_0*t);

F = a_0 + a_n_component + b_n_component;



plot(t,F);
title('Fourier Series Expansion of V_A using 5 terms');
ylabel('Amplitude');
xlabel('time');









