用最速下降法求函數的極小值,迭代兩次,計算各迭代點的函數值、梯度及其模,設初始點。
以下代碼在求解的時候並沒有嚴格按照題目中要求的迭代兩次進行計算,而是設置了最大容許誤差e,當迭代過程中g的範數小於e時候停止迭代,最終迭代了五次,如果按照題目中僅迭代兩次的話誤差就會稍微大一些。
clc
clear all
close all
% 定義允許誤差e = 0.1
e = 0.1;
Q = [2 0;0 8];
X = [1,1]';
%% 最速下降法求解極小值
iloop1 = 1;
while(1)
g = [2,8]'.* X;
gArray(:,iloop1) = g;
gNorm = norm(g);
gNormVector(iloop1) = gNorm;
Xarray(:,iloop1) = X ;
fx = 0.5*X'*Q*X;
fxVector(iloop1) = fx;
X = X-(g'*g/(g'*Q*g))*g;
iloop1 = iloop1 + 1;
if (gNorm < e)
break
end
end
%% 繪製示意圖
% 原函數fx圖形
figure
[x1,x2] = meshgrid(-1:0.01:1,-1:0.01:1);
FX = x1.^2 + 4*x2.^2;
surfc(x1,x2,FX,'LineStyle','none')
hold on
plot3(Xarray(1,:),Xarray(2,:),fxVector,'-r')
hold off
%% 顯示結果
fprintf('迭代變量座標X\n')
disp(Xarray)
fprintf('迭代路徑的函數值\n')
disp(fxVector)
fprintf('迭代點處的梯度\n')
disp(gArray)
fprintf('梯度的模\n')
disp(gNormVector)
繪製的示意圖
運算結果
迭代變量座標X
1.0000 0.7385 0.1108 0.0818 0.0123 0.0091
1.0000 -0.0462 0.1108 -0.0051 0.0123 -0.0006
迭代路徑的函數值
5.0000 0.5538 0.0613 0.0068 0.0008 0.0001
迭代點處的梯度
2.0000 1.4769 0.2215 0.1636 0.0245 0.0181
8.0000 -0.3692 0.8862 -0.0409 0.0982 -0.0045
梯度的模
8.2462 1.5224 0.9134 0.1686 0.1012 0.0187
根據計算結果來看,最終程序的迭代停止在了(0.0181,-0.0045)處,與解析解的極小值點(0,0)非常接近,函數值0.0001也與解析解的極小值點處函數0相差很小,可以認爲滿足了實際應用的需求。