简体   繁体   中英

Is there a way to find a maximum of a function of 2 variables in Matlab using max() function?

Is there a way to find a maximum of a function of 2 variables in Matlab using ‍the max() function? For example for z = x^2 +cos(y^2) that x and y are bounded in [1,10] .

It's an optimization task over a bound. So, you can use fminsearchbnd function:

f = @(x)(x(1)^2 + cos(x(2)^2));
g = @(x)-f(x);
x = fminsearchbnd(g,[1,1],[10,10],[]);

Evidently it is an optimization problem and a proper tool is to use fmincon or fminbnd , rather than max . In what follows, I listed the approaches of fmincon , fminbnd and max

  • fmincon approach
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;

which gives

>> Zmax
Zmax =  100.54 % seems not exactly the maximum 
  • fminbnd approach: since your objective function can be decomposed into two sub-optimization problems ( x and y are independent), you are able to use fminbnd on two component terms, separately, ie,
x = fminbnd(@(x) -x.^2,1,10);
y = fminbnd(@(y) -cos(y.^2),1,10);
Zmax = x^2 + cos(y^2);

which gives

>> Zmax
Zmax =  101.00
  • If you insist on using max , maybe you can try a brute-force approach like below
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)));

which gives

>> Zmax
Zmax =  101.00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM