问题如下:

首先定义目标函数:
function y = objfun(x)
% 目标函数
y = 3*x(1)^3 - 8*x(1) + 9;
end
接着定义一个试探函数:
此处有一个搜索方向,如果是一维函数,定义为1即可,如果是多为函数,则可以在不同方向上进行搜索。
function f = TryObjfun(a,StartOpint,SearchDirection)
% 目标函数在初始点+方向*步长处的函数值
f = objfun(StartOpint +a.*SearchDirection);
end
进退法函数:
function [LowBound,UpBound] = TryBound(x0,step0,StartOpint,SearchDirection)
%step0为步长
%StartOpint为起始点
%SearchDirection为搜索方向
step = step0;
f0 = TryObjfun(x0,StartOpint,SearchDirection);
x1 = x0 + step;
f1 = TryObjfun(x1,StartOpint,SearchDirection);
if f1 <= f0
while true
step = step*2;
x2 = x1 + step;
f2 = TryObjfun(x2,StartOpint,SearchDirection);
if f1 <= f2
LowBound = x0;
UpBound = x2;
break;
else
x0 = x1;f0 = f1;
x1 = x2;f1 = f2;
end
end
else
while true
step = step*2;
x2 = x0 - step;
f2 = TryObjfun(x2,StartOpint,SearchDirection);
if f0 <= f2
LowBound = x2;
UpBound = x1;
break;
else
x1 = x0;f1 = f0;
x0 = x2;f0 = f2;
end
end
end
LowBound,UpBound是在此方向上距离起始点的距离的上下界,在黄金分割法中a,b为真正的单峰区间,本题从0出发,恰好相同。
黄金分割法main_program:
clc;clear;
x0 = 0;
step0 = 0.1;
StartOpint = 0;
SearchDirection = 1;%一维函数,故取1
[LowBound,UpBound] = TryBound(x0,step0,StartOpint,SearchDirection);
a = LowBound.*SearchDirection + StartOpint
b = UpBound.*SearchDirection + StartOpint
lim = 1e-4;
lamda = 0.618;
x1 = b - lamda*(b - a);
f1 = objfun(x1);
x2 = a + lamda*(b - a);
f2 = objfun(x2);
iter = 0;
while (b - a) > lim
if f1 > f2
a = x1;
x1 = x2;
f1 = f2;
x2 = a + lamda*(b - a);
f2 = objfun(x2);
else
b = x2;
x2 = x1;
f2 = f1;
x1 = b - lamda*(b - a);
f1 = objfun(x1);
end
iter = iter +1;
end
format long
Golden_BestPoint = 0.5*(b + a)
输出极值点,iter为迭代次数。
该博客介绍了如何利用黄金分割法寻找一维函数的极值点。首先定义了目标函数和试探函数,然后通过进退法确定搜索区间的上下界。接着,运用黄金分割法进行迭代,不断缩小搜索范围,最终找到极值点。文章提供了完整的MATLAB代码实现,并给出了迭代次数作为结果。
3323

被折叠的 条评论
为什么被折叠?



