• 模拟退火算法——自带SA工具箱求解一元、二元函数的极值


    optimtool %打开工具箱,工具箱界面如下:

    fitness函数如下:

    function fitnessVal = fitness( x )
    
    % fitnessVal = sin(10*pi*x) / x;
    
    % fitnessVal = -1 * sin(10*pi*x) / x;
    
    fitnessVal = -1 * (x(1)^2 + x(2).^2 - 10*cos(2*pi*x(1)) - 10*cos(2*pi*x(2)) + 20);
    
    end
    

      

    %%主函数
    
    % I. 清空环境变量
    clear all
    clc
    
    %% II. 一元函数优化
    x = 1:0.01:2;
    y = sin(10*pi*x) ./ x;
    figure
    plot(x,y,'linewidth',1.5)
    ylim([-1.5, 1.5])  %产生伪随机序列
    xlabel('x')
    ylabel('y')
    title('y = sin(10*pi*x) / x')  
    hold on
    
    %%
    % 1. 标记出最大值点
    [maxVal,maxIndex] = max(y);
    plot(x(maxIndex), maxVal, 'r*','linewidth',2)
    text(x(maxIndex), maxVal, {[' X: ' num2str(x(maxIndex))];[' Y: ' num2str(maxVal)]})  %num2str:将数字类型转换为字符串类型
    hold on
    
    %%
    % 2. 标记出最小值点
    [minVal,minIndex] = min(y);
    plot(x(minIndex), minVal, 'ks','linewidth',2)
    text(x(minIndex), minVal, {[' X: ' num2str(x(minIndex))];[' Y: ' num2str(minVal)]})
    
    %% III. 二元函数优化
    [x,y] = meshgrid(-5:0.1:5,-5:0.1:5);
    z = x.^2 + y.^2 - 10*cos(2*pi*x) - 10*cos(2*pi*y) + 20;
    figure
    mesh(x,y,z)  %mesh:画3-D图形
    hold on
    xlabel('x')
    ylabel('y')
    zlabel('z')
    title('z = x^2 + y^2 - 10*cos(2*pi*x) - 10*cos(2*pi*y) + 20')
    
    %%
    % 1. 标记出最大值点
    maxVal = max(z(:));
    [maxIndexX,maxIndexY] = find(z == maxVal);
    for i = 1:length(maxIndexX)
    plot3(x(maxIndexX(i),maxIndexY(i)),y(maxIndexX(i),maxIndexY(i)), maxVal, 'r*','linewidth',2)
    text(x(maxIndexX(i),maxIndexY(i)),y(maxIndexX(i),maxIndexY(i)), maxVal, {[' X: ' num2str(x(maxIndexX(i),maxIndexY(i)))];[' Y: ' num2str(y(maxIndexX(i),maxIndexY(i)))];[' Z: ' num2str(maxVal)]})
    hold on
    end
    

      

  • 相关阅读:
    aes加密
    获取当前系统的版本号
    解决eclipse中出现Resource is out of sync with the file system问题
    Mac系统打开命令行终端及查看操作系统版本号的方法
    android短信拦截
    android权限大全
    mac系统下的常用命令
    android 中 系统日期时间的获取
    ubuntu tor浏览器
    Python中的random模块
  • 原文地址:https://www.cnblogs.com/Erma/p/9059291.html
Copyright © 2020-2023  润新知