蚁群算法matlab代码
时间: 2023-11-25 08:44:13 浏览: 60
这里提供一个简单的蚁群算法的 MATLAB 代码:
```matlab
% 蚁群算法
% 问题:TSP(旅行商问题)
%% 初始化
clear;clc;
% 城市坐标
city = [0.4 0.4439;
0.2439 0.1463;
0.1707 0.2293;
0.2293 0.761;
0.5171 0.9414;
0.8732 0.6536;
0.6878 0.5219;
0.8488 0.3609;
0.6683 0.2536;
0.6195 0.2634;
0.672 0.5802;
0.5878 0.5293;
0.3683 0.1988;
0.2695 0.1878;
0.145 0.4057;
0.1963 0.5707;
0.0634 0.6878;
0.4719 0.8732;
0.6049 0.9384;
0.6988 0.9384];
% 城市数量
nCity = size(city, 1);
% 蚂蚁数量
nAnt = 20;
% 迭代次数
nIter = 500;
% α、β、γ 参数
alpha = 1;
beta = 2;
gamma = 5;
% 信息素初始值
tau0 = 1 / (nCity * mean(pdist(city, 'euclidean')));
% 信息素矩阵
tau = tau0 * ones(nCity);
% 距离矩阵
dist = pdist2(city, city);
% 最优解
minPath = Inf;
minPathRecord = zeros(nCity+1, 1);
%% 迭代
for iter = 1:nIter
% 初始化蚂蚁
ant = struct('path', zeros(1, nCity+1), 'visited', false(1, nCity), 'L', 0);
ants = repmat(ant, nAnt, 1);
% 开始搜索
for k = 1:nAnt
% 选择起点
start = randi(nCity);
ants(k).path(1) = start;
ants(k).visited(start) = true;
% 搜寻路径
for i = 2:nCity
% 计算转移概率
current = ants(k).path(i-1);
unvisited = ~ants(k).visited;
t = tau(current, unvisited);
d = dist(current, unvisited);
p = (t.^alpha) .* ((1./d).^beta);
p = p / sum(p);
% 轮盘选择下一个城市
next = randsample(nCity, 1, true, p);
ants(k).path(i) = next;
ants(k).visited(next) = true;
ants(k).L = ants(k).L + dist(current, next);
end
% 回到起点
ants(k).path(nCity+1) = start;
ants(k).L = ants(k).L + dist(ants(k).path(nCity), start);
% 更新最优解
if ants(k).L < minPath
minPath = ants(k).L;
minPathRecord = ants(k).path;
end
end
% 更新信息素矩阵
delta_tau = zeros(nCity);
for k = 1:nAnt
for i = 1:nCity
j = ants(k).path(i+1);
delta_tau(ants(k).path(i), j) = delta_tau(ants(k).path(i), j) + gamma / ants(k).L;
end
end
tau = (1 - 0.01) * tau + delta_tau;
end
%% 结果展示
disp('最短路径:');
disp(minPathRecord);
disp(['最短距离:', num2str(minPath)]);
% 绘图
figure;
plot(city(:,1), city(:,2), 'ko', 'MarkerSize', 8, 'LineWidth', 1.5);
hold on;
plot(city(minPathRecord, 1), city(minPathRecord, 2), 'r-', 'LineWidth', 2);
text(city(:,1)+0.01, city(:,2)+0.01, num2str([1:nCity]'));
title(['TSP(旅行商问题)蚁群算法最优解(距离:', num2str(minPath), ')']);
xlabel('x');
ylabel('y');
axis equal;
```
阅读全文