⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gsm.m

📁 最优化学习的Matlab程序:包括最速下降法,黄金分割法,曲线拟合等.
💻 M
字号:
function [x_min,fx_min,ITER]=gsm(FUN,a,b,epsilon,ITER_max)
%GSM finds a local minimum of a function using gold section method
%epsilon   Stopping criterion
%ITER      Number of iterations
%
%   Examples
%     FUN can be specified using @:
%        [x_min,fx_min,ITER]=gsm(@sin,0,2*pi)%     
%     FUN can also be an anonymous function:
%        [x_min,fx_min,ITER]=gsm(@(x) sin(3*x),0,2*pi)
%
%   If FUN is parameterized, you can use anonymous functions to capture the 
%   problem-dependent parameters. Suppose you want to solve the equation given
%   in the function myfun, which is parameterized by its second argument c. Here
%   myfun is an M-file function such as
%
%       function f = myfun(x,c)
%       f = cos(c*x);
%
%   To solve the equation for a specific value of c, first assign the value to c.
%   Then create a one-argument anonymous function that captures that value of c 
%   and calls myfun with two arguments. Finally, pass this anonymous function to 
%   FZERO:
%
%       c = 2; % define parameter first
%       [x_min,fx_min,ITER]=gsm(@(x) myfun(x,c),-2*pi,0)
%
%   See also FMINSEARCH, FMINUNC.

%By:Ji Lin
%Email: linji@live.com
%Blog: http://linji526.spaces.live.com
%Date: 2007,2008/08/18

% If just 'defaults' passed in, return the default options
if nargin<5 
    ITER_max=500;
end
if nargin<4 
    epsilon=1e-6;
end
if nargin<3 
    b=2*pi;
end
if nargin<2 
    a=0;
end
if nargin<1 
    FUN=@(x) exp(x)*sin(x);
end


l=a+0.382*(b-a);
u=a+0.618*(b-a);
k=1;
while k<=ITER_max % Number of maximum iterations
    if feval(FUN,l)>feval(FUN,u)
        if b-l<=epsilon
            x_min=u;break;
        else
            a=l;l=u;
            u=a+0.618*(b-a);
            k=k+1;
        end
    else
        if u-a<=epsilon
            x_min=l;break;
        else
            b=u;
            u=l;
            l=a+0.382*(b-a);
            k=k+1;
        end
    end
end
fx_min=feval(FUN,x_min);ITER=k;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -