%% Filename:  StepResponseRLC.m
% Description: Matlab m-file to plot specified step response of RLC circuit
% which is voltage v(t) = (1 - e^(-at)cos(wt + theta))u(t) where
% a     = alpha = 10E5 (1/sec)
% w     = omega = 2*pi*10E6 (rad/sec)

%% Get started by cleaning things up
clear all; % clear memory
close all; % close all figures
clc;       % clear command window

%% Define and print values
L = 0.47E-3;           % set inductance to 0.47mH
a = 1E5;               % set time constant to 10usec (or exponent = 10^5)
w = 2*pi*1E6;          % set (damped) frequency of cosine to 1MHz
R = 2*a*L;             % compute resistance
C = 1/(L*(a^2 + w^2)); % compute capacitance
fprintf('R = %g Ohm, L = %g H, C = %g F\n', R, L, C);

%% Calculate response
t = linspace(0, 4/a, 1000); % set time range from 0 to 4 time constants using 1000

% v(t) with sine and cosine
% v = 1 - exp(-a*t).*cos(w*t) - (a/w)*exp(-a*t).*sin(w*t);
%
% v(t) with only cosine
v = 1 - exp(-a*t).*sqrt(1 + (a/w)^2).*cos(w*t - atan2(a, w));
%              The .* operator multiplies the two functions together for each value of t.
%
%              If you use the * operator, Matlab tries to multiply the exponention function
%              and the cosine function as a row matrix times a column matrix but they are
%              both row vectors!!

%% Plot response and its envelope
env = 1 + exp(-t*a); % compute the (top part) of exponential envelope within
                     % which response oscillates
                     
% Two functions are plotted versus t times 1E6 (time scale in microsec)
plot(t*1E6, v, t*1E6, env,'r--');

% Label plot using the following comands to make it much more meaningful!
title('Underdamped RLC Circuit with f = 10^6 Hz and \alpha = 10^5 1/sec');
grid;
xlabel('Time in Microseconds');
ylabel('Capacitor Voltage (V)');
% text(14,1.8,'f = 1E6 Hz');     % Add descriptive text to plot
% text(14,1.6,'a = 1E5 1/sec');