clear;
close all;
clc;
n = 35; %城市的數量
x = rand(1,n)*10;
y = rand(1,n)*10;
d = zeros(n,n);
for i = 1:n
for j = 1:n
if i~= j
d(i,j) = sqrt(power(x(i)-x(j),2) + power(y(i)-y(j),2));
else
d(i,j) = eps;
endend
endm = 80; %螞蟻的數量
alpha = 2;
beta = 6;
rho = 0.2; %揮發素
q = 10;
heu_f = 1./d; %先驗效應
tau = ones(n,n); % 初始化邊的資訊素
table = zeros(m,n);
iter = 1;
iter_max = 500;
route_best = zeros(iter_max,n); %最優路徑
length_best = zeros(iter_max,1); % 最優路徑的長度
%% 迭代
while iter <= iter_max
%% 初始化螞蟻出發點
start = zeros(m,1);
for i = 1:m
temp = randperm(n);
start(i) = temp(1);
end
%% 更新螞蟻的運動軌跡
table(:,1) = start;
city_index = 1:n;
for i = 1:m
for j = 2:n
has_visited = table(i,1:(j-1));
allow_index = ~ismember(city_index,has_visited);
allow = city_index(allow_index);
%%計算螞蟻轉移概率
p = allow;
for k = 1:length(allow)
p(k) = tau(has_visited(end),allow(k))^alpha * heu_f(has_visited(end),allow(k))^ beta;
endp = p / sum(p);
pc = cumsum(p); % 輪盤,cumsum是依次求行和
target_index = find(pc >= rand);
target = allow(target_index(1));
table(i,j) = target;
endend%% 計算長度
length = zeros(m,1);
for i = 1:m
route = table(i,:);
for j = 1:n-1
length(i) = length(i) + d(route(j),route(j+1));
endlength(i) = length(i) + d(route(n),route(1));
end%% 得到最佳路徑和長度
[min_length,min_index] = min(length);
if iter >1
if min_length > length_best(iter-1)
length_best(iter) = length_best(iter-1);
route_best(iter,:) = route_best(iter-1,:);
else
length_best(iter) = min_length;
route_best(iter,:) = table(min_index,:);
endelse
length_best(iter) = min_length;
route_best(iter,:) = table(min_index,:);
end%%更新代數和資訊素
iter = iter+1;
delta_tau = zeros(n,n);
for i = 1:m
for j =1:n-1
delta_tau(table(i,j),table(i,j+1)) = delta_tau(table(i,j),table(i,j+1)) + q/length(i);
endendtau = (1-rho)*tau + delta_tau;
table = zeros(m,n);
end
plot(length_best);
最大最小螞蟻的TSP問題的實現
最近,人工智慧課的作業,詳細文件就不寫了,感興趣可以聯絡我,旨在交流。include include include include include define a 2 define b 3 define q 1 define n 16 int main memset p,0,sizeof p s...
TSP問題遺傳演算法通用Matlab程式
程式一 主程式 tsp問題 又名 旅行商問題,貨郎擔問題 遺傳演算法通用matlab程式 d是距離矩陣,n為種群個數 引數a是中國31個城市的座標 c為停止代數,遺傳到第 c代時程式停止,c的具體取值視問題的規模和耗費的時間而定 m為適應值歸一化淘汰加速指數,最好取為1,2,3,4,不宜太大 alp...
蟻群演算法求解TSP問題的matlab程式
蟻群演算法求解tsp問題的matlab程式 clear all close all clc 初始化蟻群 m 31 蟻群中螞蟻的數量,當m接近或等於城市個數n時,本演算法可以在最少的迭代次數內找到最優解 c 1304 2312 3639 1315 4177 2244 3712 1399 3488 15...