鲸鱼优化算法MATLAB实现

鲸鱼优化算法matlab实现

function [best_solution, best_fitness] = woa_algorithm(obj_function, dim, search_space, max_iter, num_whales)
% 参数:
% obj_function: 优化的目标函数
% dim: 问题的维度
% search_space: 搜索空间的范围,例如 [-10, 10]
% max_iter: 最大迭代次数
% num_whales: 鲸鱼的数量

% 初始化鲸鱼的位置和速度
whales_position = rand(num_whales, dim) .* (search_space(2) - search_space(1)) + search_space(1);
whales_velocity = rand(num_whales, dim);

% 迭代优化过程
for iter = 1:max_iter
    a = 2 - iter * (2 / max_iter);  % 更新收缩参数

    % 更新每只鲸鱼的位置和速度
    for i = 1:num_whales
        r1 = rand();  % 随机数
        r2 = rand();

        A = 2 * a * r1 - a;  % 更新参数A
        C = 2 * r2;  % 更新参数C

        b = 1;  % 随机选择一只鲸鱼
        l = a * rand() - a / 2;  % 更新距离因子l
        p = rand();  % 随机概率

        if p < 0.5
            if abs(A) >= 1
                rand_whale = randi(num_whales);
                whales_position(i, :) = whales_position(rand_whale, :);
            else
                whales_position(i, :) = best_solution - A * abs(C * best_solution - whales_position(i, :));
            end
        else
            distance = abs(whales_position(b, :) - whales_position(i, :));
            whales_position(i, :) = distance .* exp(b * l) .* cos(2 * pi * l) + whales_position(b, :);

        end

        % 边界处理
        whales_position(i, :) = max(min(whales_position(i, :), search_space(2)), search_space(1));

        % 计算适应度
        fitness = obj_function(whales_position(i, :));

        % 更新最佳解
        if fitness < best_fitness
            best_solution = whales_position(i, :);
            best_fitness = fitness;
        end
    end
end

end

你可能感兴趣的:(智能算法,算法,matlab,开发语言)