%% State-Level Tolerances
% Each state level can have associated lower- and upper-state boundaries.
% These state boundaries are defined as the state level plus or minus a
% scalar multiple of the difference between the high state and the low
% state. To provide a useful tolerance region, the scalar is typically a
% small number such as 2/100 or 3/100. In general, the $\alpha\%$ region
% for the low state is defined as
%
% $$S_1\pm{\alpha\over{100}}(S_2-S_1),$$
%
% where $S_1$ is the low-state level and $S_2$ is the high-state level.
% Replace the first term in the equation with $S_2$ to obtain the
% $\alpha\%$ tolerance region for the high state.
%
% The following figure illustrates lower and upper 2% state boundaries
% (tolerance regions) for a positive-polarity bilevel waveform. The red
% dashed lines indicate the estimated state levels.

load transitionex

s = statelevels(x);
s1 = min(s);
s2 = max(s);

tl = 2;

t2 = s1+tl/100*(s2-s1);
t1 = s1-tl/100*(s2-s1);
r2 = s2+tl/100*(s2-s1);
r1 = s2-tl/100*(s2-s1);

plot(t,x)
xl = [min(t) max(t)];
xlim(xl)
ax = gca;
hold on
plot([xl;xl]',[s1 s1;s2 s2]','--','Color',ax.ColorOrder(2,:))
plot([xl;xl]',[t1 t1;r1 r1]','--','Color',ax.ColorOrder(3,:))
plot([xl;xl]',[t2 t2;r2 r2]','--','Color',ax.ColorOrder(4,:))
hold off

xlabel('Seconds')
ylabel('Volts')
title('State Levels \pm 2% Tolerance')

%% 
% Copyright 2012 The MathWorks, Inc.