MATLAB的蚁群算法代码
时间: 2024-04-01 17:13:22 浏览: 63
蚁群算法MATLAB代码
以下是一个基于MATLAB的蚁群算法的简单实现:
```
clc;
clear;
close all;
% 参数设定
alpha = 1; % 信息素重要程度因子
beta = 5; % 启发函数重要程度因子
rho = 0.5; % 信息素挥发因子
Q = 100; % 常数
num_ant = 50; % 蚂蚁数量
num_city = 20; % 城市数量
num_iter = 500; % 迭代次数
% 初始化信息素矩阵和距离矩阵
pheromone = ones(num_city, num_city);
distance = randi([1,10],num_city,num_city);
distance = triu(distance,1)+triu(distance,1)';
% 初始化最优路径
best_path = zeros(num_iter,num_city);
best_distance = inf;
% 主循环
for iter = 1:num_iter
path = zeros(num_ant,num_city);
distance_ant = zeros(num_ant,1);
for ant = 1:num_ant
current_city = randi(num_city);
visited = zeros(1,num_city);
visited(current_city) = 1;
path(ant,1) = current_city;
for city = 2:num_city
prob = zeros(1,num_city);
for next = 1:num_city
if visited(next) == 0
prob(next) = pheromone(current_city,next)^alpha * (1/distance(current_city,next))^beta;
end
end
prob = prob / sum(prob);
cumprob = cumsum(prob);
r = rand;
next_city = find(cumprob>=r,1);
visited(next_city) = 1;
path(ant,city) = next_city;
distance_ant(ant) = distance_ant(ant) + distance(current_city,next_city);
current_city = next_city;
end
distance_ant(ant) = distance_ant(ant) + distance(path(ant,num_city),path(ant,1));
end
% 更新信息素矩阵
delta_pheromone = zeros(num_city,num_city);
for ant = 1:num_ant
for city = 1:num_city-1
delta_pheromone(path(ant,city),path(ant,city+1)) = delta_pheromone(path(ant,city),path(ant,city+1)) + Q/distance_ant(ant);
end
delta_pheromone(path(ant,num_city),path(ant,1)) = delta_pheromone(path(ant,num_city),path(ant,1)) + Q/distance_ant(ant);
end
pheromone = (1-rho)*pheromone + delta_pheromone;
% 更新最优路径
[min_distance,min_index] = min(distance_ant);
if min_distance < best_distance
best_distance = min_distance;
best_path(iter,:) = path(min_index,:);
else
best_path(iter,:) = best_path(iter-1,:);
end
% 输出结果
disp(['Iteration: ',num2str(iter),' Distance: ',num2str(best_distance)]);
end
% 绘制最优路径
figure;
for i = 1:num_city-1
plot([best_path(end,i),best_path(end,i+1)],[0,1],'r','LineWidth',2);
hold on;
end
plot([best_path(end,num_city),best_path(end,1)],[0,1],'r','LineWidth',2);
axis off;
title(['Best Distance: ',num2str(best_distance)]);
```
该代码实现了基本的蚁群算法,其中包括初始化信息素和距离矩阵、初始化最优路径、主循环、更新信息素矩阵和最优路径等步骤。您可以根据需要进行修改和优化。
阅读全文