vin=12;
L=100e-6;
C=470e-6;
R=3;
k=0.25; % duty cycle

fs=20e3;
Tp=1/fs;
Ton=k*Tp;
tmax=500*Tp;
dt=50e-6; % sampling

t=0:dt:tmax; % Time values an increment dt

% conditions initiales
il(1)=0;
vc(1)=0;

duree = length(t);

for n=2:duree
    
    tinst = mod(t,Tp);
    if tinst(n)<=Ton
        D = 0;
    else
        D = 1;
    end        
    
    A=[0 -D/L; D/C -1/(R*C)];
    B=[1/L; 0];
    
    x1=[il(n-1); vc(n-1)]+dt*(A*[il(n-1); vc(n-1)]+B*vin);
        
    x2=[il(n-1); vc(n-1)]+dt*(A*x1+B*vin);
            
    x=(x1+x2)/2;
    
    il(n)=x(1);
    vc(n)=x(2);
    
    end
    
    ir=vc/R;
    
    figure(1);
    plot(t,vc);
    grid;
    
    figure(2);
    plot(t,il,t,ir);
    grid;
    