function [best_sol, best_cost] = go_mdmtsp(dist_matrix, n_iter, n_pop, n_child, prob_mut, size_pop)
% 初始化种群
pop = init_pop(size_pop, n_pop);
cost_pop = calc_cost_pop(dist_matrix, pop);
best_sol = pop(1,:);
best_cost = min(cost_pop);
for iter = 1:n_iter
% 选择操作
selected = select(pop, cost_pop, n_child);
% 交叉操作
offspring = cross(selected, dist_matrix, n_child);
% 变异操作
mutated = mutate(offspring, prob_mut, n_child);
% 计算变异后的成本
cost_mutated = calc_cost_pop(dist_matrix, mutated);
% 更新种群和成本
[pop, cost_pop] = update_pop(mutated, cost_mutated, pop, cost_pop, size_pop);
% 更新最佳解和成本
[best_sol, best_cost] = update_best(pop, cost_pop, best_sol, best_cost);
end
end
% 初始化种群
function pop = init_pop(size_pop, n_pop)
pop = randi([1,size_pop], n_pop, size_pop);
end
% 计算整个种群的成本
function cost_pop = calc_cost_pop(dist_matrix, pop)
cost_pop = cellfun(@(x) sum(dist_matrix(x,:)), pop);
end
% 选择操作
function selected = select(pop, cost_pop, n_child)
[~, I] = sort(cost_pop);
selected = pop(I(1:n_child),:);
end
% 交叉操作
function offspring = cross(selected, dist_matrix, n_child)
for i = 1:2:2*n_child-1
p1 = randi(n_child);
p2 = randi(n_child);
while p2 == p1
p2 = randi(n_child);
end
cross_points = randi(size(selected,2), 1, 2);
offspring(i,:) = [selected(p1,1:cross_points(1)) selected(p2,cross_points(1)+1:end)];
offspring(i+1,:) = [selected(p2,1:cross_points(1)) selected(p1,cross_points(1)+1:end)];
end
end
% 变异操作
function mutated = mutate(offspring, prob_mut, n_child)
for i = 1:n_child
for j = 1:size(offspring,2)
if rand < prob_mut
offspring(i,j) = randi([1,size(offspring,2)]);
end
end
end
end
% 更新种群和成本
function [pop, cost_pop] = update_pop(mutated, cost_mutated, pop, cost_pop, size_pop)
[~, I] = sort(cost_mutated);
pop(1:size_pop,:) = [mutated(I(1:size_pop),:) pop(size_pop+1:end,:)];
cost_pop(1:size_pop) = cost_mutated(I(1:size_pop));
end
% 更新最佳解和成本
function [best_sol, bes
评论已关闭