%% mysettle - Second order system step response characteristics trends

%% Initialize stuff
% clear command window and variable memory
clc; clear;

% define 2nd order system natural frequency
wn = .1;     % natural frequency
n = wn^2;    % numerator of transfer function


%% Plot step response for selected damping ratios
figure
z = 0.5 : 0.1 : 1.0;
for i = 1 : length(z)
    d = [1 2*z(i)*wn wn^2];    % denominator of transfer function
    g = tf(n, d);
    step(g);
    hold on
end
title('Step response for damping ratios between 0.5 and 1.0');
xlabel('t');
ylabel('c');
legend('0.5', '0.6', '0.7', '0.8', '0.9', '1.0');

%% Plot +/-2% settling time vs. damping ratio
n = wn^2;
z = 0.5 : 0.01 : 1.0;
for i = 1 : length(z)
    d = [1 2*z(i)*wn wn^2];    % denominator of transfer function
    g = tf(n, d);
    SI = stepinfo(g);
    Ts(i) = SI.SettlingTime;
end
figure
plot (z, Ts, '-');
% Add approximate equation to plot
hold on
Ts_approx = 4 ./ (z*wn);
plot (z, Ts_approx, '--');
title('Settling time (+/-2%) vs. damping ratio');
xlabel('zeta');
ylabel('Ts');
legend('actual', 'approx');

%% Plot +/-1% settling time vs. damping ratio
n = wn^2;
z = 0.5 : 0.01 : 1.0;
for i = 1 : length(z)
    d = [1 2*z(i)*wn wn^2];    % denominator of transfer function
    g = tf(n, d);
    SI = stepinfo(g,'SettlingTimeThreshold',0.01);
    Ts(i) = SI.SettlingTime;
end
figure
plot (z, Ts,'-');
% Add approximate equation to plot
hold on
Ts_approx = 4 ./ (z*wn);
plot (z, Ts_approx, '--');
title('Settling time (+/-1%) vs. damping ratio');
xlabel('zeta');
ylabel('Ts');
legend('actual', 'approx');

%% Plot rise time vs. damping ratio
n = wn^2;
z = 0.5 : 0.01 : 1.0;
for i = 1 : length(z)
    d = [1 2*z(i)*wn wn^2];    % denominator of transfer function
    g = tf(n, d);
    SI = stepinfo(g);
    Tr(i) = SI.RiseTime;
end
figure
plot (z, Tr, '-');
% Add approximate equation to plot
hold on
Tr_approx = (0.8 + 2.5.*z) / wn;
plot (z, Tr_approx, '--');
title('Rise time vs. damping ratio');
xlabel('zeta');
ylabel('Tr');
legend('actual', 'approx');

%% Pause for the user and remove all figures
display ('Hit Enter to continue');
pause
close all
clc