二次分配优化问题的Matlab实现:使用粒子群算法(PSO)和火焰算法(FA)的代码
【二次分配优化问题-Matlab】【使用粒子群算法(PSO),火焰算法(FA)解决二次分配优化问题Matlab代码】
二次分配问题(QAP)作为经典的组合优化难题,在设施布局、电路布线等场景频繁出现。今天我们尝试用两种群体智能算法——粒子群(PSO)和火焰算法(FA)来破解这个硬骨头。先看一个典型QAP案例:假设有3个设施要分配到3个位置,流量矩阵和距离矩阵分别为:
flow = [0 5 2; 5 0 3; 2 3 0]; % 设施间运输量 distance = [0 8 5; 8 0 10; 5 10 0]; % 位置间距目标函数计算总成本时,需要遍历所有设施对:
function cost = calculateCost(solution, flow, distance) n = length(solution); cost = 0; for i = 1:n for j = 1:n pos_i = solution(i); % 设施i的位置 pos_j = solution(j); % 设施j的位置 cost = cost + flow(i,j) * distance(pos_i, pos_j); end end end接下来实现PSO算法。这里有个小技巧——粒子位置用连续值表示,通过排序生成离散解。比如位置向量[2.3, -0.5, 4.1]经过排序后索引[2,1,3]就是设施分配方案。
% PSO核心迭代逻辑 for iter = 1:max_iter for i = 1:swarm_size % 生成离散解 [~, sol] = sort(particles(i,:)); current_cost = calculateCost(sol, flow, distance); % 更新个体最优 if current_cost < pbest_cost(i) pbest(i,:) = particles(i,:); pbest_cost(i) = current_cost; end end % 更新全局最优 [min_cost, idx] = min(pbest_cost); if min_cost < gbest_cost gbest = pbest(idx,:); gbest_cost = min_cost; end % 速度位置更新(注意边界处理) inertia = 0.729; c1 = 1.494; c2 = 1.494; velocity = inertia*velocity + c1*rand().*(pbest - particles)... + c2*rand().*(gbest - particles); particles = particles + velocity; particles = max(min(particles, pos_max), pos_min); % 限制范围 end而火焰算法的实现更强调跟随最优个体的引导。这里采用简化版FA,火焰的移动步长随着迭代动态衰减:
% FA迭代核心 alpha = 0.8; % 步长衰减系数 for iter = 1:max_iter costs = arrayfun(@(x) calculateCost(fire{x}, flow, distance), 1:n); [~, sorted_idx] = sort(costs); % 每只火焰向更优个体移动 for i = 1:n target = sorted_idx(randi(ceil(n*0.2))); % 随机选择前20%的火焰 step = alpha * (rand() - 0.5); % 带随机扰动的步长 new_fire = fire{i} + step*(fire{target} - fire{i}); % 生成新解并筛选 [~, new_sol] = sort(new_fire); new_cost = calculateCost(new_sol, flow, distance); if new_cost < costs(i) fire{i} = new_fire; end end end运行两种算法对比发现,PSO在初期收敛更快(图1中的蓝色曲线),而FA在后期表现出更强的跳出局部最优能力。这种差异源于PSO的群体信息共享机制与FA的随机扰动策略。不过要注意,对于大规模QAP问题(比如设施数超过30),可能需要引入局部搜索策略增强算法性能。
!迭代收敛曲线
【二次分配优化问题-Matlab】【使用粒子群算法(PSO),火焰算法(FA)解决二次分配优化问题Matlab代码】
图1. PSO(蓝)与FA(红)的收敛曲线对比
代码里有个有意思的细节:两种算法都采用连续空间→离散排列的转换策略。这种处理方式避免了直接操作离散变量带来的复杂性,但也可能损失部分搜索效率。在实际工业应用中,可以尝试结合置换矩阵的邻域搜索来提升优化效果。
