给我一个matlab灰狼算法代码
时间: 2023-06-24 17:07:28 浏览: 94
改进灰狼优化算法matlab代码
5星 · 资源好评率100%
下面是一个简单的 Matlab 灰狼算法实现代码,其中包含了灰狼算法的基本框架和参数设置:
```matlab
% 灰狼算法求解函数最小值
% f: 待求解的函数句柄
% dim: 待求解的变量个数
% lb: 变量的下界
% ub: 变量的上界
% max_iter: 最大迭代次数
function [best_x, best_fval] = grey_wolf_optimizer(f, dim, lb, ub, max_iter)
% 初始化灰狼群体
population_size = 30;
alpha_pos = zeros(1, dim);
alpha_score = Inf;
beta_pos = zeros(1, dim);
beta_score = Inf;
delta_pos = zeros(1, dim);
delta_score = Inf;
positions = repmat(lb, population_size, 1) + rand(population_size, dim) .* repmat(ub - lb, population_size, 1);
% 开始迭代
for iter = 1:max_iter
% 计算适应度值
scores = arrayfun(f, positions);
% 更新 alpha, beta, delta
[min_score, min_index] = min(scores);
if min_score < alpha_score
delta_score = beta_score;
delta_pos = beta_pos;
beta_score = alpha_score;
beta_pos = alpha_pos;
alpha_score = min_score;
alpha_pos = positions(min_index, :);
elseif min_score < beta_score
delta_score = beta_score;
delta_pos = beta_pos;
beta_score = min_score;
beta_pos = positions(min_index, :);
elseif min_score < delta_score
delta_score = min_score;
delta_pos = positions(min_index, :);
end
% 计算新的位置
a = 2 - iter * (2 / max_iter); % 调整 a 值
for i = 1:population_size
r1 = rand();
r2 = rand();
A1 = 2 * a * r1 - a;
C1 = 2 * r2;
D_alpha = abs(C1 * alpha_pos - positions(i, :));
X1 = alpha_pos - A1 * D_alpha;
r1 = rand();
r2 = rand();
A2 = 2 * a * r1 - a;
C2 = 2 * r2;
D_beta = abs(C2 * beta_pos - positions(i, :));
X2 = beta_pos - A2 * D_beta;
r1 = rand();
r2 = rand();
A3 = 2 * a * r1 - a;
C3 = 2 * r2;
D_delta = abs(C3 * delta_pos - positions(i, :));
X3 = delta_pos - A3 * D_delta;
positions(i, :) = (X1 + X2 + X3) / 3;
end
end
% 返回最优解
[best_fval, best_index] = min(scores);
best_x = positions(best_index, :);
end
```
使用方法:
1. 定义待求解的函数句柄 `f`。
2. 定义变量的个数 `dim`、下界 `lb` 和上界 `ub`。
3. 调用 `grey_wolf_optimizer` 函数进行求解,返回最优解 `best_x` 和最优函数值 `best_fval`。
示例代码:
```matlab
% 定义函数
f = @(x) sum(x.^2);
% 设置参数
dim = 10;
lb = -10 * ones(1, dim);
ub = 10 * ones(1, dim);
max_iter = 100;
% 求解最优解
[best_x, best_fval] = grey_wolf_optimizer(f, dim, lb, ub, max_iter);
% 输出结果
disp(['Best solution: ', num2str(best_x)]);
disp(['Best fitness: ', num2str(best_fval)]);
```
阅读全文