MATLAB基于BP神经网络PID控制程序%BPbasedPIDControlclearall;closeall;xite=0.20;%学习速率alfa=0.01;%惯性因子IN=4;H=5;Out=3;%NNStructurewi=[-0.6394-0.2696-0.3756-0.7023;-0.8603-0.2013-0.5024-0.2596;-1.07490.5543-1.6820-0.5437;-0.3625-0.0724-0.6463-0.2859;0.14250.0279-0.5406-0.7660];%wi=0.50*rands(H,IN);%隐含层加权系数wi初始化wi_1=wi;wi_2=wi;wi_3=wi;wo=[0.75760.26160.5820-0.1416-0.1325;-0.11460.29490.83520.22050.4508;0.72010.45660.76720.49620.3632];%wo=0.50*rands(Out,H);%输出层加权系数wo初始化wo_1=wo;wo_2=wo;wo_3=wo;ts=20;%采样周期取值x=[0,0,0];%比例,积分,微分赋初值u_1=0;u_2=0;u_3=0;u_4=0;u_5=0;y_1=0;y_2=0;y_3=0;Oh=zeros(H,1);%OutputfromNNmiddlelayer隐含层的输出I=Oh;%InputtoNNmiddlelayer隐含层输入error_2=0;error_1=0;fork=1:1:500%仿真开始,共500步time(k)=k*ts;rin(k)=1.0;%Delayplantsys=tf(1.2,[2081],'inputdelay',80);%建立被控对象传递函数?dsys=c2d(sys,ts,'zoh');%把传递函数离散化?[num,den]=tfdata(dsys,'v');%离散化后提取分子、分母yout(k)=-den(2)*y_1+num(2)*u_5;error(k)=rin(k)-yout(k);xi=[rin(k),yout(k),error(k),1];%经典增量式数字PID的控制算式为:()(1)(()(1))()(()2(1)(2))pidukukkekekkekkekekekBP神经网络PID的控制算式为:333123()(1)(()(1))()(()2(1)(2))ukukoekekoekoekekekx(1)=error(k)-error_1;%比例输出x(2)=error(k);%积分输出x(3)=error(k)-2*error_1+error_2;%微分输出epid=[x(1);x(2);x(3)];I=xi*wi';%隐含层的输入,即:输入层输入*权值forj=1:1:HOh(j)=(exp(I(j))-exp(-I(j)))/(exp(I(j))+exp(-I(j)));%MiddleLayer在激活函数作用下隐含层的输出endK=wo*Oh;%OutputLayer输出层的输入,即:隐含层的输出*权值forl=1:1:OutK(l)=exp(K(l))/(exp(K(l))+exp(-K(l)));%Gettingkp,ki,kd输出层的输出,即三个pid控制器的参数endkp(k)=K(1);ki(k)=K(2);kd(k)=K(3);Kpid=[kp(k),ki(k),kd(k)];du(k)=Kpid*epid;u(k)=u_1+du(k);ifu(k)=10%Restrictingtheoutputofcontroller控制器饱和环节u(k)=10;endifu(k)=-10u(k)=-10;end%以下为权值wi、wo的在线调整,参考刘金琨的《先进PID控制》dyu(k)=sign((yout(k)-y_1)/(u(k)-u_1+0.0000001));%Outputlayer输出层forj=1:1:OutdK(j)=2/(exp(K(j))+exp(-K(j)))^2;endforl=1:1:Outdelta3(l)=error(k)*dyu(k)*epid(l)*dK(l);endforl=1:1:Outfori=1:1:Hd_wo=xite*delta3(l)*Oh(i)+alfa*(wo_1-wo_2);endendwo=wo_1+d_wo+alfa*(wo_1-wo_2);%Hiddenlayerfori=1:1:HdO(i)=4/(exp(I(i))+exp(-I(i)))^2;endsegma=delta3*wo;fori=1:1:Hdelta2(i)=dO(i)*segma(i);endd_wi=xite*delta2'*xi;wi=wi_1+d_wi+alfa*(wi_1-wi_2);%ParametersUpdate参数更新u_5=u_4;u_4=u_3;u_3=u_2;u_2=u_1;u_1=u(k);y_2=y_1;y_1=yout(k);wo_3=wo_2;wo_2=wo_1;wo_1=wo;wi_3=wi_2;wi_2=wi_1;wi_1=wi;error_2=error_1;error_1=error(k);end%仿真结束,绘图figure(1);plot(time,rin,'r',time,yout,'b');xlabel('time(s)');ylabel('rin,yout');figure(2);plot(time,error,'r');xlabel('time(s)');ylabel('error');figure(3);plot(time,u,'r');xlabel('time(s)');ylabel('u');figure(4);subplot(311);plot(time,kp,'r');xlabel('time(s)');ylabel('kp');subplot(312);plot(time,ki,'g');xlabel('time(s)');ylabel('ki');subplot(313);plot(time,kd,'b');xlabel('time(s)');ylabel('kd');