% Parameters
A0 = 1e5;           % DC open-loop gain
fp = 100;           % dominant pole frequency (Hz)
fu = A0 * fp;       % unity gain bandwidth (Hz)

f = logspace(0,8,1000);   % frequency vector: 1 Hz to 100 MHz

% Open-loop gain magnitude
A_f = A0 ./ sqrt(1 + (f/fp).^2);

% Feedback factor (example: beta = 1 for unity gain buffer)
beta = 1;

% Loop gain
T_f = A_f .* beta;

% Closed-loop error: epsilon = 1/(1+T) ≈ 1/T when T>>1
epsilon = 1 ./ T_f;

% Plot open-loop gain & loop gain
figure;
subplot(2,1,1);
semilogx(f, 20*log10(A_f), 'b', 'LineWidth',1.5); hold on;
semilogx(f, 20*log10(T_f), 'r--', 'LineWidth',1.5);
xline(1e5,'k:','100 kHz'); % mark 100 kHz
xline(fu,'g:','f_u');
grid on;
xlabel('Frequency (Hz)');
ylabel('Gain (dB)');
title('Op-Amp Open-Loop Gain and Loop Gain');
legend('|A(f)|', 'Loop Gain T(f)', 'Location', 'SouthWest');

% Plot closed-loop error
subplot(2,1,2);
loglog(f, epsilon, 'm', 'LineWidth',1.5); hold on;
xline(1e5,'k:','100 kHz');
xline(fu,'g:','f_u');
grid on;
xlabel('Frequency (Hz)');
ylabel('Closed-Loop Error |V_+ - V_-| / V_{out}');
title('Closed-Loop Error vs Frequency');
legend('Error \epsilon(f)');

