% 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

figure(1)
semilogx(f, MagdB, 'k-');
title('Frequency Response Magnitude')
xlabel('Frequency (Hz)');
ylabel('dB');
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];
Mag_meas = [0.09, 0.4, 0.95, 0.99];
MagdB_meas = 20*log10(Mag_meas);

figure(2)
semilogx(f, MagdB, 'k-', f_meas, MagdB_meas, 'ko');
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.
% If the grid makes the plot messy, it can be omitted.
