% Hysteresis current controller using solution of differential equation
%
% -----------------------------------------------------------------------------------
%
% (C) 2017, Krzysztof Sozanski, Digital Signal Processing in Power Electronics Control 
% Circuits, second edition, Springer-Verlag, London, 2017. 
% 
% -----------------------------------------------------------------------------------
%
function i_out=f_inv_RL_sol_hist(i_ref,h,kr,R,L,Ep,En,RR,Ts)
tau=L/R; t=(0:RR-1)*Ts/RR; N=length(i_ref);
% initialization of variables
i_outRR=zeros(1,RR); i_out=zeros(1,RR*N); u_inv=ones(1,N)*Ep;
for n=1:N
  e=i_ref(n)-i_outRR(RR)*kr;
  if n==1
      ; % start 
  elseif u_inv(n-1)==Ep&&e<-h
    u_inv(n)=En; % switch on En
  elseif u_inv(n-1)==En&&e>h
    u_inv(n)=Ep; % switch on Ep
  else
     u_inv(n)=u_inv(n-1);
  end
  i_outRR = (exp(-t./tau)*(i_outRR(RR)-u_inv(n)/R))+u_inv(n)/R;
  i_out(1,(((n-1)*RR+1):(n*RR)))=i_outRR; %fill the output vector
end
