本文共 1918 字,大约阅读时间需要 6 分钟。
虽然MATLAB本身自带了fminsearch()函数,可以求解目标函数无梯度的最优化问题,但是感觉下面的程序在很多时候更好用,特别是自变量有边界和非线性约束的时候。
这里是John D'Errico根据Nelder-Mead单纯形直接搜索算法编写的fminsearchbnd()程序,可从
http://cn.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd--fminsearchcon
下载。也可以本地下载
%% Optimization of a simple (Rosenbrock) function, with no constraints
% The unconstrained solution is at [1,1]
rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;
% With no constraints, operation simply passes through
% directly to fminsearch. The solution should be [1 1]
xsol = fminsearchbnd(rosen,[3 3])
%% Full lower and upper bound constraints which will all be inactive
xsol = fminsearchbnd(rosen,[3 3],[-1 -1],[4 4])
%% Only lower bound constraints
xsol = fminsearchbnd(rosen,[3 3],[2 2])
%% Only upper bound constraints
xsol = fminsearchbnd(rosen,[-5 -5],[],[0 0])
%% Dual constraints
xsol = fminsearchbnd(rosen,[2.5 2.5],[2 2],[3 3])
%% Dual constraints, with an infeasible starting guess
xsol = fminsearchbnd(rosen,[0 0],[2 2],[3 3])
%% Mixed constraints
xsol = fminsearchbnd(rosen,[0 0],[2 -inf],[inf 3])
%% Provide your own fminsearch options
opts = optimset('fminsearch');
opts.Display = 'iter';
opts.TolX = 1.e-12;
n = [10,5];
H = randn(n);
H=H'*H;
Quadraticfun = @(x) x*H*x';
% Global minimizer is at [0 0 0 0 0].
% Set all lower bound constraints, all of which will
% be active in this test.
LB = [.5 .5 .5 .5 .5];
xsol = fminsearchbnd(Quadraticfun,[1 2 3 4 5],LB,[],opts)
%% Exactly fix one variable, constrain some others, and set a tolerance
opts = optimset('fminsearch');
opts.TolFun = 1.e-12;
LB = [-inf 2 1 -10];
UB = [ inf inf 1 inf];
xsol = fminsearchbnd(@(x) norm(x),[1 3 1 1],LB,UB,opts)
%% All the standard outputs from fminsearch are still returned
[xsol,fval,exitflag,output] = fminsearchbnd(@(x) norm(x),[1 3 1 1],LB,UB)
转载本文请联系原作者获取授权,同时请注明本文来自王福昌科学网博客。
链接地址:http://blog.sciencenet.cn/blog-292361-1067771.html
上一篇:立体心形曲面绘制——隐函数图形
下一篇:雪兔和猞猁数据与微分建模