how to find extremum of multivariable function in matlab

In Matlab, you can use the function fmincon to find the minimum of a multivariable function subject to constraints.

The input of fmincon is:

  • fun: the objective function to minimize
  • x0: the initial guess of the solution
  • A, b: the linear inequality constraint A*x <= b
  • Aeq, beq: the linear equality constraint Aeq*x = beq
  • lb, ub: the lower and upper bounds for the variables x

Here is an example code to find the minimum of the function f(x,y) = 3*x + 4*y subject to the constraint x + y <= 5:

main.m
fun = @(x) 3*x(1) + 4*x(2);
x0 = [0; 0];
A = [1 1];
b = 5;
lb = [0; 0];

[x, fval] = fmincon(fun, x0, A, b, [], [], lb, []);
125 chars
8 lines

The output x is the solution that minimizes the function fun, and the output fval is the minimum value of fun at x.

If you want to find the maximum of a function, you can simply negate the objective function and call fmincon with the negated function:

main.m
fun = @(x) -3*x(1) - 4*x(2);
x0 = [0; 0];
A = [1 1];
b = 5;
lb = [0; 0];

[x, fval] = fmincon(fun, x0, A, b, [], [], lb, []);

max_val = -fval;
144 chars
10 lines

In this case, max_val is the maximum value of the function -fun.

related categories

gistlibby LogSnag