% lab1_freq.m
%
% Matlab script to plot analytical and measured frequency response.
% Rich Kozick, ELEC 226

% This program is for an RC high-pass filter with analytical frequency response
% H(w) = 1 / (1 + 1/(j*w*R*C))

% Define circuit element values
R = 1.15e3;   % Ohms
C = 0.22e-6;  % Farads

% Create a vector of frequency values in Hz to evaluate the response.
% Space them logarithmically to create a Bode plot.

f = logspace(1, 5, 500);	% Hz, from 10^1 to 10^5
w = 2*pi*f;			        % frequency in radians/sec

H = 1 ./ (1 + 1./(j*w*R*C));	% Complex response, use ./ to divide vectors
Mag = abs(H);			  % Magnitude
MagdB = 20*log10(Mag);    % dB
Phase = angle(H)/pi*180;  % Phase in degrees

figure(1)
semilogx(f, MagdB, 'k-');
title('Frequency Response Magnitude')
xlabel('Frequency (Hz)');
ylabel('dB');
grid   % Remove this line to turn off grid lines

figure(2)
semilogx(f, Phase, 'k-');
title('Frequency Response Phase')
xlabel('Frequency (Hz)');
ylabel('Degrees');
grid   % Remove this line to turn off grid lines

% To compare measured data with analytical frequency response, both can
% be plotted on the same graph.
% Suppose you have 4 measured values (you will have more than 4 in lab):

f_meas = [50, 300, 2e3, 1e4]; % Frequencies (measured)
Vin  = [1, 1, 1, 1];  % Input voltage amplitude (measured)
Vout = [0.09, 0.4, 0.95, 0.99];  % Output voltage amplitude (measured)
Mag_meas = Vout ./ Vin;  % Magnitude gain, from measurements
MagdB_meas = 20*log10(Mag_meas);  % Convert gain to dB

figure(3)
semilogx(f, MagdB, 'b-', f_meas, MagdB_meas, 'ro');
legend('Analytical', 'Measured')
title('Frequency Response Magnitude')
xlabel('Frequency (Hz)');
ylabel('dB');
grid

% You can drag the legend with the mouse to a desirable place on the plot
% (usually to a location where it does not hide the graph).
% If the grid makes the plot messy, it can be omitted.

% Add figure(4) to plot your measured phase response 

