[英]Is there a way to find a maximum of a function of 2 variables in Matlab using max() function?
有没有办法使用max()
函数在 Matlab 中找到最多 2 个变量的函数? 例如,对于z = x^2 +cos(y^2)
, x
和y
有界于[1,10]
。
这是一个超出界限的优化任务。 因此,您可以使用fminsearchbnd
函数:
f = @(x)(x(1)^2 + cos(x(2)^2));
g = @(x)-f(x);
x = fminsearchbnd(g,[1,1],[10,10],[]);
显然这是一个优化问题,合适的工具是使用fmincon
或fminbnd
,而不是max
。 下面,我列出了fmincon
、 fminbnd
和max
fmincon
方法A = [];
b = [];
x0 = [5;5];
Aeq = [];
beq = [];
lb = [1;1];
ub = [10;10];
non = [];
[u,fval] = fmincon(@(u) -(u(1).^2 + cos(u(2).^2)),[1;1],A,b,Aeq,beq,lb,ub,non);
Zmax = -fval;
这使
>> Zmax
Zmax = 100.54 % seems not exactly the maximum
fminbnd
方法:由于您的目标函数可以分解为两个子优化问题( x
和y
是独立的),您可以fminbnd
在两个组件项上使用fminbnd
,即,x = fminbnd(@(x) -x.^2,1,10);
y = fminbnd(@(y) -cos(y.^2),1,10);
Zmax = x^2 + cos(y^2);
这使
>> Zmax
Zmax = 101.00
max
,也许您可以尝试像下面这样的蛮力方法x = linspace(1,10,5e3);
y = x;
[X,Y] = meshgrid(x,y);
z = @(x,y) x.^2 + cos(y.^2);
Zmax = max(max(z(X,Y)));
这使
>> Zmax
Zmax = 101.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.