% main_reacsim.m
% Function to simulate the step response of a non-linear
% chemical reactor model using the explicit Euler method.
% Purpose: Supplement to Exercise 3

clear all
global u
% Nominal variables
u=25;
x=[2.5;1];

dt=0.0005;     % Sampling interval
tf=0.1;        % Final time instant
t=0:dt:tf;     % Time horizon
N=length(t);   % Number of discrete time instants

% Vectors to store the variables and allocate space
U=zeros(N,1); Y=zeros(N,1); X=zeros(N,2);

% The main simulation loop using explicit Euler method
for k=1:N
    y=x(2);    % The measurement
    
    u=26;      % Unit step in u at time t=0
    
    U(k,1)=u;  % Save u
    Y(k,1)=y;  % Save output y
    X(k,:)=x'; % Save the states
    
    fx=fx_chemreac(0,x);  % Calculate the right hand side in dot(x)=f(x,u). u enters as global.
    x=x+dt*fx; % Calculate x_(k+1) using explicit Euler
end

figure(1)
subplot(311), plot(t,U), grid, title('Control input u')
subplot(312), plot(t,X(:,1)), grid, title('State x_1')
subplot(313), plot(t,Y), grid, title('Output y=x_2')
xlabel('Continuous time 0 \leq t \leq t_f')