值得单独一说的是fminunc, fminseach, fminbnd的区别:
fminunc只能用于求解连续函数,对于变量没有限制
fminbnd只能用于求解单变量函数,
fminsearch只能用于求解多变量函数,
%%
clc
clear all
fun = @(x) -abs(1/x);
x0 = 1;
x1= -3;
x2 = 3;
我们解这个函数的最值,在0出可以取到最值,但函数在0处没有导数:
[x,fval,exitflag,output] = fminbnd(fun,x1,x2)
[x,fval,exitflag,output] = fminsearch(fun,x0)
[x,fval,exitflag,output] = fminunc(fun,x0)
求解这个函数,可以看到结果:
x =
8.8818e-16
fval =
-1.1259e+15
exitflag =
1
output =
struct with fields:
iterations: 17
funcCount: 18
algorithm: 'golden section search, parabolic interpolation'
message: 'Optimization terminated:↵ the current x satisfies the termination criteria using OPTIONS.TolX of 1.000000e-04 ↵'
Exiting: Maximum number of function evaluations has been exceeded
- increase MaxFunEvals option.
Current function value: -1267650600228229401496703205376.000000
x =
7.8886e-31
fval =
-1.2677e+30
exitflag =
0
output =
struct with fields:
iterations: 100
funcCount: 200
algorithm: 'Nelder-Mead simplex direct search'
message: 'Exiting: Maximum number of function evaluations has been exceeded↵ - increase MaxFunEvals option.↵ Current function value: -1267650600228229401496703205376.000000 ↵'
Solver stopped prematurely.
fminunc stopped because it exceeded the function evaluation limit,
options.MaxFunctionEvaluations = 1.000000e+02.
x =
2.2204e-16
fval =
-4.5036e+15
exitflag =
0
output =
struct with fields:
iterations: 1
funcCount: 101
stepsize: 1.0000
lssteplength: 1.0000
firstorderopt: 3.0223e+23
algorithm: 'quasi-newton'
message: '↵Solver stopped prematurely.↵↵fminunc stopped because it exceeded the function evaluation limit,↵options.MaxFunctionEvaluations = 1.000000e+02.↵↵'
只有fminbnd的exitflag是1, 其他两个都是0, 因为这是一个单变量函数,所以fminsearch不能使用,又因为在0出不可导,所以fminunc也不能使用。
gophae 发布了60 篇原创文章 · 获赞 11 · 访问量 9189 私信 关注