Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Appendix B MATLAB® PROGRAMS PDF

Uploaded by

cassindrome
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Appendix B MATLAB® PROGRAMS PDF

Uploaded by

cassindrome
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

APPENDIX B

MATLAB® PROGRAMS

The following codes intend to demonstrate how each algorithm works, so they
are relatively simple and we do not intend to optimize them. In addition,
most demonstrative cases are for 2D only, though they can be extended to any
higher dimensions in principle. They are not for general-purpose optimization,
because there are much better programs out there, both free and commercial.
These codes should work using Matlab® 1 . For Octave, 2 slight modifications
may be needed.

B.l GENETIC ALGORITHMS

The following simple demo program of genetic algorithms tries to find the
maximum of
f(x) = -cos(x)e-(>x-^2.

1
Matlab, www.mathworks.com
2
J . W. Eaton, GNU Octave Manual, Network Theory Ltd, www.gnu.org/software/octave,
2002.

Engineering Optimization: An Introduction with Metaheuristic Applications. 267


By Xin-She Yang
Copyright © 2010 John Wiley & Sons, Inc.
268 MATLAB® PROGRAMS

'/, Genetic Algorithm (Simple Demo) Matlab/Octave Program


7, Written by X S Yang (Cambridge University)
% Usage: gasimple or gasimple('x*exp(-x)');
function [bestsol, bestfun, count]=gasimple(funstr)
global solnew sol pop popnew fitness fitold f range;
if nargin<l,
% Easom Function with fmax=l at x=pi
funstr='-cos(x)*exp(-(x-3.1415926)~2)';
end
range=[-10 10]; '/, Range/Domain
'/, Converting to an inline function
f=vectorize(inline(funstr));
'/, Initializing the parameters
rand('state' ,0'); '/, Reset the random generator
popsize=20; '/, Population size
MaxGen=100; '/, Max number of generations
count=0; 7, counter
nsite=2; '/, number of mutation sites
pc=0.95; '/, Crossover probability
pm=0.05; '/, Mutation probability
nsbit=16; '/, String length (bits)
7, Generating the initial population
popnew=init_gen(popsize,nsbit);
fitness=zeros(l,popsize); % fitness array
'/, Display the shape of the function
x=range(l):0.1:range(2); plot(x,f(x));
% Initialize solution <- initial population
for i=l:popsize,
solnew(i)=bintodec(popnew(i,:));
end
7, Start the evolution loop
for i=l:MaxGen,
y. Record as the history
fitold=fitness; pop=popnew; sol=solnew;
for j=l:popsize,
% Crossover pair
ii=floor(popsize*rand)+1; jj=floor(popsize*rand)+1;
'/, Cross over
if pc>rand,
[popnew(ii,:),popnew(jj,:)]=...
crossover(pop(ii,:),pop(jj,:));
'/, Evaluate the new pairs
count=count+2;
evolve(ii); evolve(jj);
end
B.l GENETIC ALGORITHMS 269

% Mutation at n sites
if pm>rand,
kk=floor(popsize*rand)+l; count=count+l;
popnew(kk,:)=mutate(pop(kk,:),nsite);
evolve(kk);
end
end V, end for j
% Record the current best
bestfun(i)=max(fitness);
bestsol(i)=mean(sol(bestfun(i)==fitness));
end
% Display results
subplot (2,1,1); plot(bestsol); titleCBest estimates');
subplot(2,l,2); plot(bestfun); title('Fitness');
7. All the sub functions
'/, generation of the initial population
function pop=init_gen(np,nsbit)
% String length=nsbit+l with pop(:,l) for the Sign
pop=rand(np,nsbit+l)>0.5;
% Evolving the new generation
function evolve(j)
global solnew popnew fitness fitold pop sol f;
solnew(j)=bintodec(popnew(j,:));
fitness(j)=f(solnew(j));
if fitness(j)>fitold(j),
pop(j,:)=popnew(j,:);
sol(j)=solnew(j);
end
% Convert a binary string into a decimal number
function [dec]=bintodec(bin)
global range;
% Length of the string without sign
nn=length(bin)-l;
num=bin(2:end); % get the binary
'/. Sign=+1 if bin(l)=0; Sign=-l if bin(l)=l.
Sign=l-2*bin(l);
dec=0;
% floating point/decimal place in a binary string
dp=floor(log2(max(abs(range))));
for i=l:nn,
dec=dec+num(i)*2~(dp-i);
end
dec=dec*Sign;
% Crossover operator
function [c,d]=crossover(a,b)
270 MATLAB® PROGRAMS

nn=length(a)-l;
'/, generating a random crossover point
cpoint=floor(nn*rand)+l;
c=[a(l:cpoint) b(cpoint+l:end)];
d=[b(l:cpoint) a(cpoint+l:end)];
% Mutatation operator
function anew=mutate(a,nsite)
nn=length(a); anew=a;
for i=l:nsite,
j=floor(rand*nn)+l;
anew(j)=mod(a(j)+l,2);
end

B.2 SIMULATED ANNEALING

The implemented simulated annealing intends to find the minimum of Rosen-


brock's function
f(x,y) = (l-x)2 + 100(y-x2)2.
t Simulated Annealing (by X-S Yang, Cambridge University)
% Usage: sa_demo
dispO Simulating ... it will take a minute or so!');
% Rosenbrock's function with f*=0 at (1,1)
fstr='(l-x)~2+100*(y-x~2)~2';
% Convert into an inline function
f=vectorize(inline(fstr));
'/, Show the topography of the objective function
range=[-2 2 - 2 2 ] ;
xgrid=range(l):0.1:range(2); ygrid=range(3):0.1:range(4);
[x,y]=meshgrid(xgrid,ygrid);
surfc(x,y,f(x,y));
% Initializing parameters and settings
T_init = 1 . 0 ; % Initial temperature
T_min = le-10; °/, Final stopping temperature
F_min = -le+100; °/, Min value of the function
max_rej=2500; '/, Maximum number of rejections
max_run=500; °/, Maximum number of runs
max_accept = 15; °/0 Maximum number of accept
k = 1; '/, Boltzmann constant
alpha=0.95; '/, Cooling factor
Enorm=le-8; '/, Energy norm (eg, Enorm=le-8)
guess=[2 2]; '/, Initial guess
°/0 Initializing the counters i,j etc
i= 0; j = 0; accept = 0; totaleval = 0;
B.2 SIMULATED ANNEALING 271

'/« Initializing various values


T = T_init;
E_init = f(guess(l),guess(2));
E_old = E_init; E_new=E_old;
best=guess; '/„ initially guessed values
7, Starting the simulated annealling
while ((T > T_min) & (j <= max_rej) & E_new>F_min)
i = i+1;
% Check if max numbers of run/accept are met
if (i >= max_run) I (accept >= max_accept)
% Cooling according to a cooling schedule
T = alpha*T;
totaleval = totaleval + i;
% reset the counters
i = 1; accept = 1;
end
% Function evaluations at new locations
ns=guess+rand(l,2)*randn;
E_new = f(ns(l),ns(2));
% Decide to accept the new solution
DeltaE=E_new-E_old;
% Accept if improved
if (-DeltaE > Enorm)
best = ns; E_old = E_new;
accept=accept+l; j = 0;
end
% Accept with a small probability if not improved
if (DeltaE<=Enorm & exp(-DeltaE/(k*T))>rand ) ;
best = ns; E_old = E_new;
accept=accept+l;
else

end
% Update the estimated optimal solution
f_opt=E_old;
end
'/, Display the final results
disp(strcat('Obj function :',fstr));
disp(strcat('Evaluations :', num2str(totaleval)));
disp(strcat('Best solution:', num2str(best)));
disp(strcat('Best objective:', num2str(f_opt)));
272 MATLAB® PROGRAMS

B.3 PARTICLE SWARM OPTIMIZATION

The following PSO program tries to find the global minimum of Michaelwicz's
2D function

f(x,y) = -sin(z)sm20(-) -sin(y)sin20(^).


π 7Γ

°/0 Particle Swarm Optimization (by X-S Yang, Cambridge University)


% Usage: pso_demo(number_of.particles,Num_iterations)
"/. eg: best=pso_demo(20,15);
% where best=[xbest ybest zbest] %an n by 3 matrix

function [best]=pso_demo(n,Num_iterations)
% n=number of particles; Num_iterations=number of iterations
if nargin<2, Num_iterations=15; end
if nargin<l, n=20; end
'/. Michaelwicz Function f*=-1.801 at [2.20319,1.57049]
fstr='-sin(x)*(sin(x~2/pi))~20-sin(y)*(sin(2*y~2/pi))~20';
% Converting to an inline function and vectorization
f=vectorize(inline(fstr));
'/, range= [xmin xmax ymin ymax] ;
range=[0404];
%
°/o Setting the parameters: alpha, beta
alpha=0.2; beta=0.5;
I
'/, Grid values of the objective for visualization only
Ndiv=100;
dx=(range(2)-range(1))/Ndiv;dy=(range(4)-range(3))/Ndiv;
xgrid=range(l):dx:range(2); ygrid=range(3):dy:range(4);
[x,y]=meshgrid(xgrid,ygrid);
z=f(x,y);
'/, Display the shape of the function to be optimized
figure(l); surfc(x,y,z);
χ
best=zeros(Num_iterations,3); °/0 initialize history
'/, Start Particle Swarm Optimization
'/, generating the initial locations of n particles
[xn,yn]=init_pso(n,range);
% Display the particle paths and contour of the function
figure(2);
% Start iterations
for i=l:Num_iterations,
% Show the contour of the function
contour(x,y,z,15); hold on;
B.4 HARMONY SEARCH 273

% Find the current best location (xo,yo)


zn=f(xn,yn);
zn_min=min(zn);
xo=min(xn(zn==zn_min));
yo=min(yn(zn==zn_min));
zo=min(zn(zn==zn_min));
'/, Trace the paths of all roaming particles
'/, Display these roaming particles
plot(xn,yn,'.',xo,yo,'*'); axis(range);
% Move all the particles to new locations
[xn,yn]=pso_move(xn,yn,xo,yo,alpha,beta,range);
drawnow;
% Use "hold on" to display paths of particles
hold off;
% History
best(i,l)=xo; best(i,2)=yo; best(i,3)=zo;
end '/,'/.'/,'/.'/. end of iterations
% All subfunctions are listed here
'/, Intial locations of n particles
function [xn,yn]=init_pso(n,range)
xrange=range(2)-range(l); yrange=range(4)-range(3);
xn=rand(1,n)*xrange+range(1);
yn=rand(l,n)*yrange+range(3);
7, Move all the particles toward (xo.yo)
function [xn,yn]=pso_move(xn,yn,xo,yo,a,b,range)
nn=size(yn,2); °/0a=alpha, b=beta
xn=xn.*(1-b)+xo.*b+a.*(rand(1,nn)-0.5);
yn=yn.*(1-b)+yo.*b+a.*(rand(1,nn)-0.5);
[xn,yn]=findrange(xn,yn,range);
% Make sure the particles are within the range
function [xn,yn]=findrange(xn,yn,range)
nn=length(yn);
for i = l : n n ,
if xn(i)<=range(l), xn(i)=range(l); end
if xn(i)>=range(2), xn(i)=range(2); end
if yn(i)<=range(3), yn(i)=range(3); end
if yn(i)>=range(4), yn(i)=range(4); end
end

B.4 HARMONY SEARCH

This simple program for Harmony Search intends to find the global minimum
of Rosenbrock's function f(x,y) = (1 - x)2 + 100(y — x2)2, which can easily
be extended to any dimension.
274 MATLAB® PROGRAMS

'/, Harmony Search (Simple Demo) by X-S Yang (Cambridge University)


'/, Usage: hs_demo
'/. or hs_demo('(x-D"2+100*(y-x~2)~2',25000);
function [solution,fbest]=hs_simple(funstr,MaxAttempt)
disp('It may take a few minutes . . . ' ) ;
'/. MaxAttempt=25000; % Max number of Attempt
if nargin<2, MaxAttempt=25000; end
if nargin<l,
% Rosenbrock's Banana function with the global f*=0 at (1,1).
funstr = >(l-xl)-2+100*(x2-xl~2)~2';
end
% Converting to an inline function
f=vectorize(inline(funstr));
ndim=2; '/«Number of independent variables
'/. The range of the objective function
ranged, :) = [-5 5 ] ; range(2,: ) = [-5 5 ] ;
% Pitch range for pitch adjusting
pa_range=[100 100];
% Initial parameter setting
HS_size=20; "/.Length of solution vector
HMacceptRate=0.95; °/,HM Accepting Rate
PArate=0.7; '/.Pitch Adjusting rate
'/. Generating Initial Solution Vector
for i=l:HS_size,
for j=l:ndim,
x(j)=range(j,1)+(range(j,2)-range(j,1))*rand;
end
HM(i, :) = x;
HMbest(i) = f(x(l), x(2));
end '/,'/<, for i
'/. Starting the Harmony Search
for count = 1:MaxAttempt,
for j = l:ndim,
if (rand >= HMacceptRate)
'/, New Search via Randomization
x(j)=range(j,1)+(range(j,2)-range(j,l))*rand;
else
'/. Harmony Memory Accepting Rate
x(j) = HM(fix(HS_size*rand)+l,j);
if (rand <= PArate)
'/. Pitch Adjusting in a given range
pa=(range(j,2)-range(j,l))/pa_range(j);
x(j)= x(j)+pa*(rand-0.5);
end
end
B.5 FIREFLY ALGORITHM 275

end '/,'/, for j


% Evaluate the new solution
fbest = f(x(l), x(2));
% Find the best in the HS solution vector
HSmaxNum = 1; HSminNum=l;
HSmax = HMbest(l); HSmin=HMbest(l);
for i = 2:HS_size,
if HMbest(i) > HSmax,
HSmaxNum = i;
HSmax = HMbest(i);
end
if HMbest(i)<HSmin,
HSminNum=i;
HSmin=HMbest(i);
end
end
'/. Updating the current solution if better
if fbest < HSmax,
HM(HSmaxNum, :) = x;
HMbest(HSmaxNum) = fbest;
end
solution=x; % Record the solution
end VI, for count (harmony search)

B.5 FIREFLY ALGORITHM

Here we use a non-smooth multi-peak function that has 2d peaks in the d-


dimensional case
d d
2
/(χ)=(^|^|)βχ Ρ (-α^χΙ ). (B.l)

In the simplest 2-D case, we have

f{x,y) = {\x\ + \y\)e-a^+^\ (B.2)

which has four equal peaks. In order to obtain the analytical solutions, we
have to differentiate it, but this function does not have derivative at (0,0).
However, the function is symmetric in x and y. That is, the function remains
the same when x and y are interchanged. So we only have to find the solution
in the first quadrant x > 0 and y > 0. In the first quadrant, we have

| ί = [1 - 2ax(x + y)}e-a{x2+y2) = 0, (B.3)


276 MATLAB® PROGRAMS

and
^- = [\- 2ay{x + y)}e-a{x2+y2) = 0. (B.4)

The symmetry in x and y implies that £» = y» at the stationary points, so


we have
1 - 2 a x * ( x , + x„) = 1 -Aaxl = 0, (B.5)
which gives
x* = Λ=· (Β.6)
2y/a
For a = 0.0625, we have x* = 2. So the four peaks are at

(a;,, y.) = (2,2), (2, - 2 ) , (-2,2), ( - 2 , - 2 ) . (B.7)

The maximum at the peaks is / , = 4 e x p ( - l / 2 ) « 2.4261226. A demonstra­


tive code for the Firefly Algorithm is as follows:
% F i r e f l y Algorithm by X-S Yang (Cambridge University)
y, Usage: firefly_demo([number_of.fireflies,MaxGeneration])
% eg: firefly_demo( [25,20]);
function [best]=firefly_demo(instr)
"/, n=number of f i r e f l i e s
y. MaxGeneration=number of pseudo time s t e p s
if n a r g i n < l , instr=[25 20]; end
n = i n s t r ( l ) ; MaxGeneration=instr(2);
r a n d ( ' s t a t e ' , 0 ) ; % Reset the random generator
'/, Four peak functions
funstr='(abs(x)+abs(y))*exp(-0.0625*(x~2+y~2))';
y, Converting t o an i n l i n e function
f=vectorize(inline(funstr));
'/, range= [xmin xmax ymin ymax] ;
range=[-5 5 - 5 5 ] ;
%
alpha=0.2; % Randomness 0—1 (highly random)
gamma=1.0; % Absorption coefficient
χ
% Grid values are used for display only
Ndiv=100;
dx=(range(2)-range(1))/Ndiv; dy=(range(4)-range(3))/Ndiv;
[x,y]=meshgrid(range(l):dx:range(2),range(3):dy:range(4));
z=f(x,y);
'/, Display the shape of the objective function
figure(l); surfc(x,y,z);
%
% generating the initial locations of n fireflies
[xn,yn,Lightn]=init_ffa(n,range);
B.5 FIREFLY ALGORITHM 277

% Display the paths of fireflies in a figure with


% contours of the function to be optimized
figure(2);
'A I t e r a t i o n s or pseudo time marching
for i=l:MaxGeneration, °/°/°/°/,°l. s t a r t i t e r a t i o n s
% Show t h e contours of t h e function
contour(x,y,z,15); hold on;
% Evaluate new solutions
zn=f(xn.yn);
% Ranking the fireflies by their light intensity
[Lightn,Index]=sort(zn);
xn=xn(Index); yn=yn(Index);
xo=xn; yo=yn; Lighto=Lightn;
% Trace the paths of all roaming fireflies
plot(xn,yn,'.','markersize',10,'markerfacecolor','g');
°/0 Move all fireflies to the better locations
[xn,yn]=ffa_move(xn,yn,Lightn,xo.yo,...
Lighto,alpha,gamma,range);
drawnow;
% Use "hold on" to show the paths of fireflies
hold off;
end V/°/°/X end of iterations
best(:,l)=xo'; best(:,2)=yo'; best(:,3)=Lighto';
'/, All subfunctions are listed here
'/, The initial locations of n fireflies
function [xn,yn,Lightn]=init_ffa(n,range)
xrange=range(2)-range(l);
yrange=range(4)-range(3);
xn=rand(1,n)*xrange+range(1);
yn=rand(1,n)*yrange+range(3);
Lightn=zeros(size(yn));
'/, Move all fireflies toward brighter ones
function [xn,yn]=ffa_move(xn,yn,Lightn,xo.yo,...
Lighto,alpha,gamma,range)
ni=size(yn,2); nj=size(yo,2);
for i=l:ni,
% The attractiveness parameter beta=exp(-gamma*r)
for j=l:nj,
r=sqrt((xn(i)-xo(j))~2+(yn(i)-yo(j))~2) ;
if Lightn(i)<Lighto(j) , */, Brighter and more attractive
beta0=l; beta=betaO*exp(-gamma*r."2);
xn(i)=xn(i).*(l-beta)+xo(j).*beta+alpha.*(rand-0.5);
yn(i)=yn(i).*(l-beta)+yo(j).*beta+alpha.*(rand-0.5);
end
end 7, end for j
278 MATLAB® PROGRAMS

end */, end for i


[xn,yn]=findrange(xn,yn,range);
% Make sure the f i r e f l i e s are within t h e range
function [xn,yn]=findrange(xn,yn,range)
for i = l : l e n g t h ( y n ) ,
if x n ( i ) < = r a n g e ( l ) , x n ( i ) = r a n g e ( l ) ; end
if xn(i)>=range(2), x n ( i ) = r a n g e ( 2 ) ; end
if yn(i)<=range(3), y n ( i ) = r a n g e ( 3 ) ; end
if yn(i)>=range(4), y n ( i ) = r a n g e ( 4 ) ; end
end

If you run the Matlab program with 25 fireflies, all four peaks can be found
simultaneously.

B.6 LARGE SPARSE LINEAR SYSTEMS

To solve a large-scale sparse linear system, Krylov subspace methods are most
efficient in most cases. For example, the conjugate gradient method is an
efficient solver for
Au = b,
where A is a normal matrix. In our simple implementation, it requires that
A is real and symmetric.

% Simple implementation of the Conjugate Gradient Method


% by X. S. Yang (Cambridge University)
% This p a r t forms a known system Av=b for demo only
n=50; % t r y t o use n=50, 250, 500, 5000
A=randn(n,n); % generate a random square matrix
A=(A+A')/2; % make sure A i s symmetric
v=(l:n)'; °/0 t h e t a r g e t s o l u t i o n
b=A*v; '/, form a l i n e a r system

% Solve the system by the conjugate g r a d i e n t method


u=rand(n,1); % i n i t i a l guess uO
r=b-A*u; % i n t i a l rO
d=r; 7. i n t i a l d0=r0
delta=10~ (-5) ; 70 accuracy

while max(abs(r))>delta
alpha=r'*r/(d'*A*d); '/„ alpha_n
K=r'*r; °/0 temporary value
u=u+alpha*d; % u_{n+l}
r=r-alpha*A*d; '/, r_{n+l}
beta=r'*r/K; '/, beta_n
B.7 NONLINEAR OPTIMIZATION 279

d=r+beta*d; 7, d_{n+l}
u' °/0 d i s p u on t h e screen
end

Initially, you can run the program using a small n = 50, which will show
almost exact answers. Then, you can try n = 500 and 5000 as further numeric
experiments.

B.7 NONLINEAR OPTIMIZATION

To write our own codes is often time-consuming. In many cases, we can


simply use existing well-tested programs. For example, the optimizer f mincon
of the Matlab optimization toolbox can be used to solve many optimization
problems. Let us use two examples to demonstrate how to turn a nonlinear
optimization problem into simple Matlab codes.

B.7.1 Spring Design


The original spring design optimization is

minimize f(x) = (2 + L)dw2, (B.8)

subject to gx(x) = 1 - 7?7%wi < 0


„ /_\ id2—wd _i_ i ^ <~ r\
x L
92\ ) — 12566dw 3 -w 4 "·" 5108™^ - υ (B.9)
ι
g3(x) = 1 - -ψ^ < °
g4(x) = *±L· - 1 < 0
The simple bounds are

0.05 < w < 2.0, 0.25 < d < 1.3, 2.0 < L < 15.0. (B.10)

In order to use the Matlab optimization toolbox/function f mincon, we can


write it using x — (w,d,L)T = (xi,X2,%3)T\ a n d we have

minimize f{x) = {2 + xz)x2x\, {B.ll)

subject to gi(x) = 1 - 7 ^ 7 g^ < 0

92\X) - 12566ϊ2χ?-χί +
5108x^ _ L
- U
(B.12)
g3(x) = l - i f g ^ < o
g4(x) = ^ i - 1< 0
with simple bounds
0.05 < xi < 2.0, 0.25 < x2 < 1.3, 2.0 < x3 < 15.0. (B.13)
280 MATLAB® PROGRAMS

These bounds can be written as

Lb<x< Üb, (B.14)

with the lower bound


Lb = [0.05; 0.25; 2.0]; (B.15)
and the upper bound
Ub= [2.0; 1.3; 15.0]; (B.16)
Starting from an educated guess

x0 = [0.1; 0.5; 10]; (B.17)

we can write the program as the following matlab code


% Spring Design Optimization using Matlab fmincon
function spring
x0=[0.1; 0 . 5 ; 10];
Lb=[0.05; 0.25; 2 . 0 ] ; Ub=[2.0; 1.3; 1 5 . 0 ] ;
% call matlab optimization toolbox
[x,fval]=fmincon(<3objfun,x0, [],[],[], [] ,Lb,Ub,Snonfun)

'/, Objective function


function f=objfun(x)
f=(2+x(3))*x(l)-2*x(2);

'/„ Nonlinear constraints


function [g,geq]=nonfun(x)
'/, Inequality constraints
g(l)=l-x(2)~3*x(3)/(7178*x(l)~4);
gtmp=(4*x(2)-2-x(l)*x(2))/(12566*x(2)*x(l)~3-x(l)~4);
g(2)=gtmp+l/(5108*x(l)~2)-l;
g(3)=l-140.45*x(l)/(x(2)-2*x(3));
g(4)=x(l)+x(2)-1.5;
% Equality c o n s t r a i n t s [none]
geq= [] ;

If we run this simple Matlab program, we can obtain the optimal solution

x* « (0.0500,0.2500,9.9877), (B.18)

which gives / m i n ~ 0.0075. This solution is better than the best solution
obtained by Cagnina et al.

/* « 0.012665, (B.19)

at
x* w (0.051690, 0.356750, 11.287126). (B.20)
B.7 NONLINEAR OPTIMIZATION 281

B.7.2 Pressure Vessel


The standard pressure vessel optimization can be written as

minimize f(x) = 0.6224dirL + l.7781d2r2 + 3.1661d2L + 19.84d?r, (B.21)

subject to gx(x) = -d1 + 0.0193r < 0


g2(x) = -d2 + 0.00954r < 0
g3(x) = -nr2L - ^r3 + 1296000 < 0
g4(x) = L - 240 < 0
(B.22)
with simple bounds 0.0625 < dlt d2 < 99 x 0.0625, and 10.0 < r, L < 200.0.
To transform into the Matlab code, we now use x = (xi,x2,xs,X4)T =
(di,d2,r,L)T to rewrite the above optimization as

minimize f(x) = 0.6224ΧΙΖ 3 :Ε4 + 1.7781ζ22;3 + 3.1661χ^ 4 + 19.84^x 3 ,

subject to gi(x) = —xi +0.0193x3 < 0


g2(x) = -χ2 + 0.00954x3 < 0
g3(x) = Xi - 240 < 0
g4(x) = -Kxjx4 - ψχ3 + 1296000 < 0.
Here we have interchanged the third and forth inequalities so the the first
three are simple inequalities, while the last inequality is nonlinear. The first
three inequalities gi,g2,g3 can be written as

Ax < b, (B.23)

where
Ί 0 0.0193 0^
0 - 1 0.00954 0 | , 6 = ( 0 |. (B.24)
^0 0 0 1,
The simple bounds can be rewritten as

Lb = [d;d;10;10]; Ub = [99 * d; 99 * d; 200; 200], (B.25)

where d — 0.0625. With the above reformulation, we can program it as the


following Matlab code
% Design Optimization of a Pressure Vessel
function pressure_vessel
x0=[l; 1; 20; 50];
d=0.0625;
% Linear inequality constraints
A=[-l 0 0.0193 0;0 -1 0.00954 0;0 0 0 1];
282 MATLAB® PROGRAMS

b=[0; 0; 240];
% Simple bounds
Lb=[d; d; 10; 10]; Ub=[99*d; 99*d; 200; 200];
options=optimset('Display','iter','TolFun',le-08);
[x,fval]=fmincon(@objfun,xO,A,b, [] , [] ,Lb,Ub,<2nonfun,options)
% The objective function
function f=objfun(x)
f=0.6224*x(l)*x(3)*x(4)+1.7781*x(2)*x(3)~2 . ..
+3.1661*x(l)~2*x(4)+19.84*x(l)~2*x(3)
'/, Nonlinear constraints
function [g,geq]=nonfun(x)
% Nonlinear inequality
g=-pi*x(3)"2*x(4)-4*pi/3*x(3)"3+1296000;
7. Equality constraint [none]
geq= [];
In the above code, '...' means the line continues. That is, the current line and
the next line should form a single line in Matlab. This '...' is only added for
typesetting the code to avoid an ugly long line.
If we run the above program, we have
x* « (0.7782,0.3846,40.3196,200.0000)τ, (Β.26)
with / m i n fa 5885.33, which is lower that the best solution /* « 6059.714
at so* « (0.8125, 0.4375, 42.0984, 176.6366), obtained by Cagnina et al.
It is worth pointing out that we have relaxed the constraints of d\ and efe
in the above implementation, as d\ and d? can only take discrete values of
integer multiples of 0.0625 in the original design problem. If we impose these
constraints, our program will produce exactly the same results as the best
solution /* m 6059.714 obtained by Cagnina et al. Here it is left as an exercise
for the readers to modify the program to achieve this. You can either add
extra constraints or change the formulation slightly.
From the above two examples (spring and pressure vessel design), we can
see that the optimizer f mincon in Matlab is a very good optimizer and suitable
for many applications.

REFERENCES

1. L. C. Cagnina, S. C. Esquivel, C. A. Coello, "Solving engineering optimization


problems with the simple constrained particle swarm optimizer", Informatica,
32, 319-326 (2008).
2. J. W. Eaton, "Gnu Octave Manual", Network Theory Ltd, 2002.
3. O. Sigmund, "A 99 line topology optimization code written in Matlab", Struct.
Multidisc. Optim., 21, 120-127 (2001).
4. Matlab's optimization toolbox, www.mathworks.com

You might also like