how to find extrema of multivariable function in matlab in matlab

To find extrema of a multivariable function in Matlab, you can use the fmincon function which is provided by the Optimization Toolbox. The fmincon function minimizes a function subject to constraints. To find the maximum of a function, you need to negate the function and minimize it.

Here is an example code to find the minimum and maximum of a function of two variables using fmincon:

main.m
% Define the function to be minimized/negated
f = @(x) -(x(1)^2 + x(2)^2 - 2*x(1)*x(2));

% Define lower and upper bounds of variables
lb = [-1, -1];
ub = [2, 2];

% Define initial guess for variables
x0 = [0, 0];

% Define options structure with optimization parameters
options = optimoptions('fmincon','Display','iter');

% Call fmincon to minimize/negate the function
[x_min, f_min] = fmincon(f, x0, [], [], [], [], lb, ub, [], options);
[x_max, f_max] = fmincon(f, x0, [], [], [], [], lb, ub, @nonlinear_con, options); % point to nonlinear constraint

% Define nonlinear constraint
function [c,ceq] = nonlinear_con(x)
    c = -x(1)^2 - x(2)^2 + 2;
    ceq = [];
end

% Print results
fprintf('Min: x = [%f, %f], f = %f\n', x_min(1), x_min(2), -f_min);
fprintf('Max: x = [%f, %f], f = %f\n', x_max(1), x_max(2), f_max);
822 chars
27 lines

In this code, the function f represents the function to be minimized/negated. The lb and ub variables represent the lower and upper bounds of the search space. The x0 variable represents the initial guess for the optimization algorithm. You also need to define the options structure with optimization parameters. Finally, you can call the fmincon function to minimize/negate the function.

The fmincon function will return the optimal variable values in x_min and x_max, as well as the optimized function value in f_min and f_max. Note that to find the maximum of a function, you also need to define a nonlinear constraint that negates the function when the constraint is satisfied, as I have shown in this example.

related categories

gistlibby LogSnag