MATLAB: How can i increase the speed of this program

problem with speed

This is a program of AGC. whenever i am trying to optimize this program with genetic algorithm it is taking too much time, more than a week. please tell me how can i solve this problem: function J=agc(Ki) Tp1=20; Tp2=20; Kp1=120; Kp2=120; T12=0.0866; Tch1=0.3; Tch2=0.3; Tg1=0.08; Tg2=0.08; R1=2.4; R2=2.4; a12=-1; apf1=0.5; apf2=0.5; D1=1/Kp1; D2=1/Kp2; B1=D1+(1/R1); B2=D2+(1/R2);
A=[(-1/Tp1) 0 (-Kp1/Tp1) (Kp1/Tp1) 0 0 0; 0 (-1/Tp2) (-a12*Kp2/Tp2) 0 (Kp2/Tp2) 0 0; (2*pi*T12) (-2*pi*T12) 0 0 0 0 0; 0 0 0 (-1/Tch1) 0 (1/Tch1) 0; 0 0 0 0 (-1/Tch2) 0 (1/Tch2); (-1/(R1*Tg1)) 0 0 0 0 (-1/Tg1) 0; 0 (-1/(Tg2*R2)) 0 0 0 0 (-1/Tg2)];
B=[0 0;0 0;0 0;0 0;0 0;(apf1/Tg1) 0;0 (apf2/Tg2)];
C=[(-Kp1/Tp1) 0;0 (-Kp2/Tp2);0 0;0 0;0 0;0 0;0 0];
u1=0; u2=0; u=[u1;u2]; g1=0.01; g2=0; g=[g1;g2]; dt=0.01; x(1,:)=[0 0 0 0 0 0 0]; x0=(x(1,:)); t(1)=0; k=1; tw=k*dt;
while tw~=80 tw=k*dt; ts=t(k); tf=ts+dt; tspan=[ts tf];
[ts,xs]=ode45(@xnew,tspan,x0,[],g,u);
n=size(xs,1);
k=k+1;
t(k,1)=ts(n);
x(k,:)=xs(n,:);
x0=(x(k,:));
x1=x(k,1);
x2=x(k,2);
x3=x(k,3);
ACE1=(B1*x1)+x3;
ACE2=(B2*x2)+(a12*x3);
u1=u1-Ki(1)*dt*ACE1;
u2=u2-Ki(2)*dt*ACE2;
u=[u1;u2];
g=[g1;g2];
T= sym('T');
fun=((x1'*x1)+(x2'*x2)+(x3'*x3))*dt;
J=int(fun,T,0,80);
clear ts xs
end
function xdot=xnew(t,x,g,u)
xdot=A*x+B*u+C*g;
end
end

Best Answer

While I could not read much of your code (in the future, please mark code with the {} Code button), there are several deficiencies that I saw.
  • You are using a symbolic variable for integration. Don't do that for a numeric problem. Instead, use numeric integration, probably best with the integral function.
  • I did not see your call to ga. But generally, fmincon works much faster on smooth problems, and patternsearch works faster and more reliably on nonsmooth problems. See Table for Choosing a Solver.
  • Because you have an ODE solution and numerical integration in your objective function, if you take my advice and use fmincon as you optimizer, you should keep in mind the suggestions in Optimizing an ODE, especially about choosing larger-than-default finite differences.
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation