首页 > 代码库 > 一维搜索
一维搜索
%% 一维搜索方法
clc;
clear all;
close all;
x = -2:0.01:2;
y = 3*x.^2 - 4.*x + 2;
plot(x,y,‘r-.‘,‘linewidth‘,2);
hold on
%% 初始化
x0 = 0;%初始值;
k = 1;%初始步长;
LL = 0.002;%终止条件
amin = -1;
bmax = 1;
lamda = 0.382;
x1 = amin + lamda *(bmax-amin);
x2 = amin +(1- lamda )*( bmax-amin);
fx1 = fun_f(x1);
fx2 = fun_f(x2);
p1 =line([x1,x1],[0,fx1],‘linewidth‘,2);
% hold on
p1 = line([x2,x2],[0,fx2],‘linewidth‘,2);
c = [];
%% 搜索开始
while bmax-amin > LL
if fx1 > fx2
amin = x1;
% bmax = bmax;
x1 = x2;
fx1 = fx2;
x2 = amin + (1-lamda) *(bmax-amin);
fx2 = fun_f(x2);
else
% amin = amin;
bmax = x1;
x2 = x1;
fx2 = fx1;
x1 = amin + lamda*(bmax-amin);
fx1 = fun_f(x1);
end
p1 =line([x1,x1],[0,fx1],‘linewidth‘,2);
% hold on
p1 = line([x2,x2],[0,fx2],‘linewidth‘,2);
k = k +1;
c = [c;[amin,bmax,x1,x2,fx1,fx2]];
end
function fx =fun_f(x)
fx = 3*x^2 - 4*x + 2;
end
一维搜索