function fpa_demo
% FPA算法演示
% 目标函数定义
objFunc = @(x) x.^2;
% 参数设置
popSize = 20; % 种群大小
dim = 1; % 问题维度
maxGen = 100; % 最大迭代次数
p = 0.8; % 全局搜索概率
% 初始化种群
X = rand(popSize, dim) * 10 - 5; % 随机初始化种群
fitness = arrayfun(objFunc, X); % 计算初始适应度
% FPA主循环
for gen = 1:maxGen
for i = 1:popSize
if rand < p % 全球传播
L = levy(dim); % 利维飞行步长
dX = L .* (X(i,:) - bestSolution(X, fitness));
Xnew = X(i,:) + dX;
else % 局部传播
epsilon = rand;
j = randi([1, popSize]);
k = randi([1, popSize]);
while k == j
k = randi([1, popSize]);
end
Xnew = X(i,:) + epsilon * (X(j,:) - X(k,:));
end
% 边界检查
Xnew = max(min(Xnew, 5), -5);
% 更新解
fnew = objFunc(Xnew);
if fnew <= fitness(i)
X(i,:) = Xnew;
fitness(i) = fnew;
end
end
end
% 输出最优解
[optFitness, optIndex] = min(fitness);
optSolution = X(optIndex, ;
fprintf(‘最优解: x = %f, f(x) = %f\n’, optSolution, optFitness);
end
function L = levy(d)
% 利维飞行步长
beta = 1.5;
sigma = (gamma(1 + beta) * sin(pi * beta / 2) / (gamma((1 + beta) / 2) * beta * 2^((beta - 1) / 2)))^(1 / beta);
u = randn(1, d) * sigma;
v = randn(1, d);
step = u ./ abs(v).^(1 / beta);
L = 0.01 * step;
end
function bestSol = bestSolution(X, fitness)
% 寻找当前最优解
[~, bestIndex] = min(fitness);
bestSol = X(bestIndex, ;
end