蝴蝶优化算法(Butterfly Optimization Algorithm,BOA)是一种新兴的智能优化算法,它模拟了蝴蝶寻找食物和休息的行为,通过不断搜索和调整参数,最终找到最优解。
以下是蝴蝶优化算法的MATLAB实现代码:
function [best_fit,best_pos,history] = BOA(fitness_func, dim, lb, ub, max_iter, pop_size, r0, alpha, beta)% fitness_func: fitness function, dim: dimension of variables% lb: lower bound, ub: upper bound, max_iter: maximum number of iterations% pop_size: population size, r0: initial radius, alpha: control parameter, beta: control parameter% best_fit: best fitness value, best_pos: best position, history: fitness convergence history% Initialize population
pop_pos = repmat(lb, pop_size, dim) + rand(pop_size, dim) .* repmat(ub-lb, pop_size, 1);
pop_fit = feval(fitness_func, pop_pos);[best_fit, best_idx] = min(pop_fit);
best_pos = pop_pos(best_idx, :);% Initialize radius
r = r0;% Initialize history
history = zeros(max_iter, 1);
history(1) = best_fit;
for i = 2:max_iter
% Update radius
r = r * alpha;
% Generate new population
new_pop_pos = repmat(best_pos, pop_size, 1) + randn(pop_size, dim) .* repmat(r, pop_size, 1);
% Boundary control
new_pop_pos(new_pop_pos < lb) = lb(new_pop_pos < lb);
new_pop_pos(new_pop_pos > ub) = ub(new_pop_pos > ub);
% Evaluate fitness
new_pop_fit = feval(fitness_func, new_pop_pos);
% Update population
for j = 1:pop_size
if new_pop_fit(j) < pop_fit(j)
pop_pos(j, :) = new_pop_pos(j, :);
pop_fit(j) = new_pop_fit(j);
if new_pop_fit(j) < best_fit
best_pos = new_pop_pos(j, :);
best_fit = new_pop_fit(j);
end
else
p = rand;
if p < exp(-(new_pop_fit(j)-pop_fit(j))/beta)
pop_pos(j, :) = new_pop_pos(j, :);
pop_fit(j) = new_pop_fit(j);
end
end
end
% Save history
history(i) = best_fit;
end
end
其中,fitness_func为适应度函数,dim为变量维度,lb和ub为变量的取值范围,max_iter为最大迭代次数,pop_size为种群大小,r0为初始半径,alpha和beta为控制参数。
使用示例:
% Define fitness function
fitness_func = @(x) sum(x.^2, 2);
% Set parameters
dim = 2;
lb = -10;
ub = 10;
max_iter = 100;
pop_size = 50;
r0 = 0.1;
alpha = 0.95;
beta = 1.5;
% Run algorithm
[best_fit, best_pos, history] = BOA(fitness_func, dim, lb, ub, max_iter, pop_size, r0, alpha, beta);
% Plot convergence history
plot(history);
xlabel('Iteration');
ylabel('Fitness');
title('BOA');
best_fit
best_pos
history
>> BOATest
best_fit =
1.2643e-09
best_pos =
1.0e-04 *
-0.2104 -0.2866
history =
3.1749
2.4151
1.6751
1.1871
0.8874
0.6266
0.3422
0.1804
0.0995
0.0280
0.0005
0.0001
0.0001
0.0001
0.0001
0.0001
0.0001
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000