%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% File: opt_k_oven.m
% Computation of the optimal temperatures of a n-segment oven
% which minimizes the quadratic cost.
x0=0; xf=1000;              % Initial and final states
a=1/2; b=1/2;               % Difference equation coefficients
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MainString='opt_k_oven'; Stampa=1;
figure(1); clf; n_max=6;
cost=zeros(1,n_max);
u=zeros(n_max);
for n=(1:n_max);            % For n varying from 1 to n_max
    Rn=[b zeros(1,n-1)];
    for ii=(2:n)
        Rn(ii)=a*Rn(ii-1);  % Reachability matrix
    end
    u(n,1:n)=flipud(Rn'*inv(Rn*Rn')*(xf-a^n*x0)); % Optimal input sequence
    xn=[x0 zeros(1,n)];
    for ii=(1:n)
        xn(ii+1)=a*xn(ii)+b*u(n,ii);        % State evolution
    end
    plot(0:n,xn,'*-'); hold on                   % Data plot
    text(n-1/2,0.95*xn(n+1),['n=' num2str(n)])
    cost(n)=norm(u(n,:));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(1)
title('Temperatures of the steel bars')
ylabel('Temperatures th(i) the steel bars')
xlabel('Number n of oven segments'); grid on
if Stampa;    eval(['print -depsc ' MainString '_' num2str(gcf)]); end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(2); clf;
for n=(1:n_max);            % For n varying from 1 to n_max
    plot(n:n_max,u(n:n_max,n),'*-r'); hold on
end
xlim([1 n_max])
title('Optimal temperatures of the oven segments')
ylabel('Temperatures u(i) of the oven segments')
xlabel('Number n of oven segments'); grid on
if Stampa;    eval(['print -depsc ' MainString '_' num2str(gcf)]); end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(3); clf
plot((1:n), cost(1:n),'*-m'); % Plot the cost function
title('Heating cost function |u| for n=[ 1 2 3 4 5 6]')
ylabel('Cost function |u|')
xlabel('Number n of oven segments'); grid on
if Stampa;    eval(['print -depsc ' MainString '_' num2str(gcf)]); end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
