You are on page 1of 6

Contoh 1 Dynamic Programming

function [OptimalTour,mincost]=Untitled2(~)
% Demo to demonstrate how pdist() can find distances between all points of
2 sets of points.
% Requires the Statistics and Machine Learning Toolbox because of the
pdist() and squareform() functions.
workspace; % Make sure the workspace panel is showing.
format short g;
format compact;
fontSize = 28;
NumOfCities=10;
G=[0,0];
G1=[1,3]; G2=[1,7]; G3=[3,9]; G4=[5,3]; G5=[1,1];
G6=[9,5]; G7=[9,9]; G8=[11,1]; G9=[15,7];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
points1=[G];
points2=[G1;G2;G3;G4;G5;G6;G7;G8;G9];
% Plot all the points
% Get the distance from every point to every other point.
pDist = pdist([points1;points2]);
% That's hard to interpret though, so
% let's reshape that into a nice table
D = squareform(pDist)
%B=tril(D);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Primes=primes(NumOfCities*10);
NumOfDataSets=1;
for i=2:NumOfCities
NumOfDataSets=NumOfDataSets+nchoosek(NumOfCities,i);
end
Data(NumOfDataSets).S=[];
Data(NumOfDataSets).l=0;
Data(NumOfDataSets).cost=inf;
Data(NumOfDataSets).pre=[];
Data(NumOfDataSets).m=[];
LookUpTable(NumOfDataSets)=0;
Data(1).S=[1];
Data(1).l=1;
Data(1).cost=0;
Data(1).Pre=[];
Data(1).m=[];
for s=2:NumOfCities
Data(s).S=[Data(1).S,s];
Data(s).l=s;
Data(s).cost=D(s,1);
Data(s).Pre=1;
Data(s).m=1;
LUT=calcLUT(Data(s).S,s,Primes);
LookUpTable(s)=LUT;
end
IndexStartPrevStep=2; %index into Data that marks the beginning of the
previous step
IndexLastStep=NumOfCities; %index into Data that marks the end of the
previous step
CurrentData=IndexLastStep; %index into Data that marks the current dataset
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%This is the main Dynamic Programming loop
for s=3:NumOfCities
%generate possible sets with s-1 cities out of the possible N-1 cities
%(not including city 1)
TempSets=nchoosek(2:NumOfCities,s-1);
NumOfSets=size(TempSets);
for j=1:NumOfSets(1) %iterate through all the sets
for k=1:NumOfSets(2) %iterate through all the elements in each set
SminuskSet=[1,TempSets(j,1:k-1),TempSets(j,k+1:NumOfSets(2))]; %this is the
set S-{k}
candidatecost(2:length(SminuskSet))=inf;
indices=[];
for mm=2:length(SminuskSet) %choose a city in S-{k} that will be last
LUV=calcLUT(SminuskSet,SminuskSet(mm),Primes);
index=find(LUV==LookUpTable(IndexStartPrevStep:IndexLastStep));
index=index+IndexStartPrevStep-1;
if index==0
candidatecost(mm)=inf;
else
candidatecost(mm)=Data(index).cost+D(SminuskSet(mm),TempSets(j,k));
indices(mm)=index;
end
end
[mincost,indexcost]=min(candidatecost(2:end));
CurrentData=CurrentData+1;
Data(CurrentData).S=[1,TempSets(j,:)];
Data(CurrentData).l=TempSets(j,k);
Data(CurrentData).cost=mincost;
Data(CurrentData).Pre=indices(indexcost+1);
Data(CurrentData).m=SminuskSet(indexcost+1);
LookUpTable(CurrentData)=calcLUT(Data(CurrentData).S,TempSets(j,k),Primes);
end
end
IndexStartPrevStep=IndexLastStep+1;
IndexLastStep=CurrentData;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mm=0;
%Now add the distance back from the last city to city 1
for i=IndexStartPrevStep:IndexLastStep
mm=mm+1;
candidatecost(mm)=Data(i).cost+D(Data(i).l,1);
end
%Find the one that minimizes the total distance
[mincost,indexcost]=min(candidatecost);
Temp=Data(IndexStartPrevStep+indexcost-1);
%Generate the optimal tour by traversing back from the last city to its
%predecessors
OptimalTour=1;
while ~isempty(Temp.Pre)
OptimalTour=[OptimalTour,Temp.l];
Temp=Data(Temp.Pre);
end
ZY=min(candidatecost)
OptimalTour=[OptimalTour,1];
W=OptimalTour;

function LUT=calcLUT(vec,last,Primes)
j=length(vec);
LUT=Primes(last);
for i=2:j
LUT=LUT*Primes(vec(i));
end
Contoh 2 PSO
function [rute_optimum, jarak_minimum,t]=psofortsp(ba,bb,np,itmax)
%dx=matriks jarak
%ba,bb,np = batas atas (10),batas bawah (-10), jumlah partikel (50)
%itmax = iterasi maksimum
%rute_optimum = rute tsp terbaik (optimal)
%jarak_minimum = jarak dari rute tsp yang terbaik
%t = waktu komputasi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fontSize = 28;
NumOfCities=10;
G1=[1,3]; G2=[1,7]; G3=[3,9]; G4=[5,3]; G5=[1,1];
G6=[9,5]; G7=[9,9]; G8=[11,1]; G9=[15,7]; G=[0,0];
points1=[G];
points2=[G1;G2;G3;G4;G5;G6;G7;G8;G9];
% Plot all the points
% Get the distance from every point to every other point.
pDist = pdist([points1;points2]);
% That's hard to interpret though, so
% let's reshape that into a nice table
dx = squareform(pDist);
A=tril(dx);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%step 1:
t=cputime;
%inisialisasi secara random partikel xi dan kecepatan vi dalam ruang
%pencarian problem p-dimensi
np=50; %jumlah partikel
c=10;
nk=c;
ba=10; %batas atas
bb=-10; %batas bawah
x=rand(np,nk)*(ba-bb)+bb; %inisialisasi partikel xi
v=rand(np,nk); %inisialisasi kecepatan vi
%mengurutkan nilai random secara ascending untuk mendapatkan rute
[min1 perm]=sort(x,2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
perm_tsp=[perm perm(:,1)] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%step 2: evaluasi nilai fungsi tujuan jarak total tiap rute


jarak=zeros(np,1);
for i=1:np
x1=perm_tsp(i,:);
jarak(i)=jartsp(x1,dx); %memanggil fungsi perhitungan jarak rute tsp
end
f=jarak;

%step 3: memperbaharui nilai Pbest dan Gbest partikel awal


Pbest=x; %posisi terbaik individu (best local)
fbest=f; %fungsi tujuan terbaik
[minf,idk]=min(fbest);
Gbest=x(idk,:); %posisi terbaik swarm (best global)
minftot=[];
minfk=[];

%step 4: memperbaharui posisi dan kecepatan partikel


it=3; %setting iterasi
rhomax=1.2;
rhomin=0.8; %rentang nilai inersia yang digunakan
itmax=10;
while it<itmax
r1=rand;
r2=rand;
rho=rhomax-((rhomax-rhomin)/itmax)*it; %bobot inersia
for j=1:np
v(j,:)=rho.*v(j,:)+r1.*(Pbest(j,:)-x(j,:)-x(j,:))+r2.*(Gbest-x(j,:));
x(j,:)=x(j,:)+v(j,:);
end
%penyelesaian agar x tidak melanggar interval (bb,ba)
for i=1:np
for j=1:nk-1
if x(i,j)>ba
x(i,j)=ba;
end
if x(i,j)<bb
x(i,j)=bb;
end
end
end
%mengurutkan nilai random untuk mendapatkan rute dari yang terkecil ke
%terbesar
[min1 perm]=sort(x,2);
perm_tsp=[perm perm(:,1)]; %permutasi rute tsp
%evaluasi nilai fungsi tujuan permutasi tsp
jarak=zeros(np,1);
for i=1:np
x1=perm_tsp(i,:);
jarak(i)=jartsp(x1,dx); %memanggil fungsi perhitungan jarak rute tsp
end
f=jarak;
%memperbarui fbest,Pbest, Gbest
changerow=f<fbest;
fbest=fbest.*(1-changerow)+f.*changerow;
Pbest(find(changerow),:)=x(find(changerow),:);
[minf,idk]=min(fbest);
Gbest=Pbest(idk,:);
Gbest=min(Pbest);
it=it+1; %penambahan jumlah iterasi
end

%step 5:output solution


lastbest=Pbest; %nilai random partikel terbaik pada iterasi terakhir
[min1 perm]=sort(lastbest,2);
perm_tsp=[perm perm(:,1)]; %rute tsp kembali ke kota asal
%evaluasi nilai fungsi tujuan pada iterasi tahap akhir
jarak=zeros(np,1);
for i=1:np;
x1=perm_tsp(1,:);
jarak(i)=jartsp(x1,dx); %memanggil fungsi perhitungan jarak rute tsp
end
f=jarak; %fungsi tuuan
[jarak_minimum,idk]=min(f);
t=cputime-t;
function jarak=jartsp(x1,dx)
[r,c]=size(x1);
k=c-1; %jumlah kota dalam rute tsp
s=0; %jarak awal di kota pertama
for j=1:k
s=s+dx(x1(j),x1(j+1)); %pengakumulasian jarak rute tsp
end
jarak=s
Contoh 3 FPA
function [best,fmin,N_iter]=FPA_tsp(para,D)
% Default parameters
if nargin<1,
para=[25 0.8];
end
n=para(1); % Population size, typically 10 to 25
p=para(2); % probabibility switch

% Iteration parameters
N_iter=500; % Total number of iterations
fitnessMSE = ones(1,N_iter);
d=10; % Dimension of the search variables
minposisi=-30;
maksposisi=30;
Lb=minposisi*ones(1,d);
Ub=maksposisi*ones(1,d);

% Initialize the population/solutions


for i=1:n,
Sol(i,:)=Lb+(Ub-Lb).*rand(1,d);
% To simulate the filters use fitnessX() functions in the next line
Fitness(i)=Fun(Sol(i,:));
end

% Find the current best


[fmin,I]=min(Fitness);
best=Sol(I,:);
S=Sol;

% Start the iterations -- Flower Algorithm


for t=1:N_iter,
% Loop over all bats/solutions
for i=1:n,
% This L should replace by Levy flights
% Formula: x_i^{t+1}=x_i^t+ L (x_i^t-gbest)
if rand<p,
%% L=rand;
L=Levy(d);
dS=L.*(Sol(i,:)-best);
S(i,:)=Sol(i,:)+dS;
% Check if the simple limits/bounds are OK
S(i,:)=simplebounds(S(i,:),Lb,Ub);
% If not, then local pollenation of neighbor flowers
else
epsilon=rand;
% Find random flowers in the neighbourhood
% JK=randperm(n);
% As they are random, the first two entries also random
% If the flower are the same or similar species, then
% they can be pollenated, otherwise, no action.
% Formula: x_i^{t+1}+epsilon*(x_j^t-x_k^t)
S(i,:)=S(i,:)+ epsilon.*(best-Sol(i,:));
% S(i,:)=S(i,:)+epsilon*(Sol(JK(1),:)-Sol(JK(2),:));
% Check if the simple limits/bounds are OK
S(i,:)=simplebounds(S(i,:),Lb,Ub);
end
% Evaluate new solutions
% To simulate the filters use fitnessX() functions in the next line
Fnew=Fun(S(i,:));
% If fitness improves (better solutions found), update then
if (Fnew<Fitness(i)),
Sol(i,:)=S(i,:);
Fitness(i)=Fnew;
End

% Update the current global best


if Fnew<fmin,
best=S(i,:) ;
fmin=Fnew ;
end
% p = p-((N_iter-t)/N_iter)*(0.1);
end
% Display results every 100 iterations
end
% figure, plot(1:N_iter,fitnessMSE);
% Output/display

% Application of simple constraints


function s=simplebounds(s,Lb,Ub)
% Apply the lower bound
ns_tmp=s;
I=ns_tmp<Lb;
ns_tmp(I)=Lb(I);
% Apply the upper bounds
J=ns_tmp>Ub;
ns_tmp(J)=Ub(J);
% Update this new move
s=ns_tmp;

% Draw n Levy flight sample


function L=Levy(d)
% Levy exponent and coefficient
% For details, see Chapter 11 of the following book:
% Xin-She Yang, Nature-Inspired Optimization Algorithms, Elsevier, (2014).
lamda=1.7;
sigma=(gamma(1+lamda)*sin(pi*lamda/2)/(gamma((1+lamda)/2)*lamda*2^((lamda-
1)/2)))^(1/lamda);
u=randn(1,d)*sigma^2;
v=randn(1,d);
step=u./abs(v).^(1/lamda);
L=step;

function z=Fun(u)
%% Booth's function V
z=(u(1)+2.*u(2)-7).^2+(2.*u(1)+u(2)-5).^2;

You might also like