// common emitter amplifier, triangular output voltage
// all voltages normalized by Vcc
// all currents normalized by Vcc/R

// initialization
clear
npoint=720;
i=1:npoint;
t=(i-0.5)/npoint;
pa=4*t(1:(npoint/2))-1;
pb=3-4*t((npoint/2+1):npoint);
pattern=[pa,pb];

MceQ=1/2; // you can adjust this, move the quiescent operating point from the optimal position
JcQ=1-MceQ;

Mm=min([MceQ, 1-MceQ]);

scf(1);

for k=1:100
  
    m(k)=k/100; // modulation index
    mce=MceQ+m(k)*Mm*pattern;
    jc=1-mce;
    mr=1-mce;
    pcc=1*jc; // 1* is for educational purposes, a symbol for Vcc*
    pd=mce.*jc;
    pr=mr.*jc;
    prac=(jc-JcQ).*(mr-(1-MceQ));
    Pcc(k)=mean(pcc);
    Pd(k)=mean(pd);
    Pr(k)=mean(pr);
    Prac(k)=mean(prac);
    efficiency(k)=Prac(k)/Pcc(k)*100;
    
    drawlater()
    
    clf(1);
    
    subplot(421)
    plot2d(t,mce,rect=[0 0 1 1],nax=[0 5 0 5])
    xtitle('','t/T','vce/Vcc')
      
    subplot(423)
    plot2d(t,jc,rect=[0 0 1 1],nax=[0 5 0 5])
    xtitle('','t/T','ic/(Vcc/R)')
    
    subplot(425)
    plot2d(t,mr,rect=[0 0 1 1],nax=[0 5 0 5])
    xtitle('','t/T','vr/Vcc')
    
    subplot(422)
    plot2d(t,pcc,rect=[0 0 1 1],nax=[0 5 0 5])
    xtitle('','t/T','pcc/(Vcc^2/R)')
    
    subplot(424)
    plot2d(t,pd,rect=[0 0 1 1],nax=[0 5 0 5])
    xtitle('','t/T','pd/(Vcc^2/R)')
    
    subplot(426)
    plot2d(t,pr,rect=[0 0 1 1],nax=[0 5 0 5])
    xtitle('','t/T','pr/(Vcc^2/R)')
    
    subplot(427)
    plot2d(mce,jc,style=0,rect=[0 0 1 1])
    xtitle('','vce/Vcc','ic/(Vcc/R)')
    
    subplot(428)
    plot2d(t,prac,rect=[0 0 1 1],nax=[0 5 0 5])
    xtitle('','t/T','prac/(Vcc^2/R)')

    drawnow()

end

scf(2);
clf(2);
plot2d(m,Pcc,rect=[0 0 1 1.1*JcQ],style=color("black"))
plot2d(m,Pr,rect=[0 0 1 1.1*JcQ],style=color("blue"))
plot2d(m,Prac,rect=[0 0 1 1.1*JcQ],style=color("green"))
plot2d(m,Pd,rect=[0 0 1 1.1*JcQ],style=color("red"))
xtitle('','Vm/Vmmax','Pcc [black], Pr [blue], Pd [green], Prac [red], all /(Vcc^2/R)')

scf(3);
clf(3);
plot2d(m,efficiency)
xtitle('','Vm/Vmmax','efficiency [%]')

