matlab一维搜索,用进退法确定搜索区间

一维搜索是优化算法的基础部分。搜索极小值首先要确定搜索区间,最常用的区间搜索就是进退法。根据进退法的本意,我重新优化了进退法搜索算法。如果有什么不对的地方,请网友们提出来。

function [a,b]=searchInterval(f,x0,h,t)
% Function:
%        searchInterval
% Input:
%        f: function;
%        x0: initial point;
%        h:step;
%        t :t>1;
% Output:
%        [a,b]: interval;
% Call: (none)
%
%----------------------------------------
% Principle:
% Application:
% Attention:
% Example:
% >>> f=@(t)t^4-t^2-2*t+5;
% >>> [a,b]=searchInterval(f,0,0.1)
% a =
%     0.3000
% b =
%     1.5000
% See also
%----------------------------------------
% Designer: William Song
% Date: 26-Apr-2015
% Path: D:\MATLAB\mywork\numerical\searchInterval.m

if nargin<=3,t=2;
    if nargin<=2,h=1;
        if nargin<=1,x0=0;
        end
    end
end

y0=f(x0);
x=x0+h;
y=f(x);
if y>y0,
    h=-h;         % x0,x<-x,x0
    x0=x;         % y0<-y;
    x=x0+h;
    y=f(x);       % y



下面是通常采用的算法。其实这个算法有一个小毛病,那就是第一次出现y=y0时,会报错。比较一下是不是做到了优化。

function [a,b]=searchInterval(f,x0,h,t)
% Function:
%        searchInterval
% Input:
%        f: function;
%        x0: initial point;
%        h:step;
%        t :t>1;
% Output:
%        [a,b]: interval;
% Call: (none)
% 
%----------------------------------------
% Principle: 
% Application: 
% Attention: 
% Example: 
% >>> f=@(x)x^3-2*x+1;
% >>> [a,b]=searchInterval(f)
% a =
%      0
% b =
%      3
% See also 
%----------------------------------------
% Designer: William Song
% Date: 26-Apr-2015
% Path: D:\MATLAB\mywork\numerical\searchInterval.m

if nargin<=3,t=2;
    if nargin<=2,h=1;
        if nargin<=1,x0=0;
        end
    end
end

y0=f(x0);k=0;
while 1
    x=x0+h;
    y=f(x);
    if y
            k=k+1;
        else
            a=min(xx,x);b=max(xx,x);return;
        end
    end
end


你可能感兴趣的:(matlab,代码,matlab,优化)