%% Plantilla del profesor (funciones_de_sensibilidad_familia_curvas.m) adaptada al examen 1
clear; close all;
s = tf('s');

G = 500/(s*(s+500));          % planta: motor
ganancias = [50 125 1000];    % los tres K del examen

L = {}; S = {}; Su = {}; Si = {}; T = {};   % cajas para guardar una FT por cada K
i = 0;
for K = ganancias
    i = i + 1;
    D = tf(K,1);               % controlador P
    L{i}  = D*G;               % función de lazo
    S{i}  = 1/(1+L{i});        % r -> e
    Su{i} = D/(1+L{i});        % r -> u
    Si{i} = G/(1+L{i});        % d -> y
    T{i}  = D*G/(1+L{i});      % r -> y
end
leg = "K=" + string(ganancias);

figure(1); sgtitle('Respuesta en frecuencia')
subplot(2,2,1); bodemag(S{:});  legend(leg); title('S(s)');   grid on
subplot(2,2,2); bodemag(Si{:}); legend(leg); title('S_i(s)'); grid on
subplot(2,2,3); bodemag(Su{:}); legend(leg); title('S_u(s)'); grid on
subplot(2,2,4); bodemag(T{:});  legend(leg); title('T(s)');   grid on

figure(2); sgtitle('Respuesta al escalón')
subplot(2,2,1); step(S{:});  legend(leg); title('S(s)');   grid on
subplot(2,2,2); step(Si{:}); legend(leg); title('S_i(s)'); grid on
subplot(2,2,3); step(Su{:}); legend(leg); title('S_u(s)'); grid on
subplot(2,2,4); step(T{:});  legend(leg); title('T(s)');   grid on

%% Números para el apartado 1.3
for i = 1:3
    [Gm,Pm,~,Wcp] = margin(L{i});
    Ms = getPeakGain(S{i});  Mt = getPeakGain(T{i});
    fprintf('K=%4d  MF=%5.1f deg @ %6.1f rad/s  MG=%g  Ms=%.2f dB  Mt=%.2f dB\n', ...
        ganancias(i), Pm, Wcp, Gm, mag2db(Ms), mag2db(Mt))
end
