用模拟退火算法求解带约束的二元函数极值问题之二:用MATLAB绘图验证
1.MATLAB代码段
%% I. 清空环境变量
clear all
clc
%% II. 二元函数绘图
[x,y] = meshgrid(-5:0.1:5,-5:0.1:5);
z = (6*x)./(2 + power(x,2) + power(y,2) + eps) + 5.*sin(x) + 3.*cos(y) + 50;
figure
mesh(x,y,z)
hold on
xlabel('x')
ylabel('y')
zlabel('z')
title('z = 6*x/(2 + x*x + y*y) + 5*sin(x) + 3*cos(y) + 50')
%%
% 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
%%
% 1. 标记出最小值点
minVal = min(z(:));
[minIndexX,minIndexY] = find(z == minVal);
for i = 1:length(minIndexX)
plot3(x(minIndexX(i),minIndexY(i)),y(minIndexX(i),minIndexY(i)), minVal, 'r*','linewidth',2)
text(x(minIndexX(i),minIndexY(i)),y(minIndexX(i),minIndexY(i)), minVal, {[' X: ' num2str(x(minIndexX(i),minIndexY(i)))];[' Y: ' num2str(y(minIndexX(i),minIndexY(i)))];[' Z: ' num2str(minVal)]})
hold on
end
2.绘图结果
3.结论
观察可知,绘图最大值约为60.1051,最小值约为41.3242,与模拟退火算法求解结果基本一致。