how to find the extremum in matlab

To find the extremum (minimum or maximum) of a function in Matlab, you can use the fminsearch function for unconstrained optimization or fmincon for constrained optimization.

Here's an example of how to use fminsearch to find the minimum of a function:

main.m
% Define the function to minimize
fun = @(x) x(1)^2 + x(2)^2;

% Set the initial guess
x0 = [1, 1];

% Call fminsearch to find the minimum
[xmin, fval] = fminsearch(fun, x0);

% Print the results
fprintf('Minimum found at x = [%.4f, %.4f] with a value of %.4f\n', xmin(1), xmin(2), fval);
289 chars
12 lines

Here's an example of how to use fmincon to find the minimum of a function subject to a constraint:

main.m
% Define the function and constraint
fun = @(x) x(1)^2 + x(2)^2;
nonlcon = @(x) x(1) + x(2) - 1;

% Set the initial guess
x0 = [1, 1];

% Set the bounds for the variables
lb = [-inf, -inf];
ub = [inf, inf];

% Call fmincon to find the minimum
[xmin, fval] = fmincon(fun, x0, [], [], [], [], lb, ub, nonlcon);

% Print the results
fprintf('Minimum found at x = [%.4f, %.4f] with a value of %.4f\n', xmin(1), xmin(2), fval);
423 chars
17 lines

Note that in both examples, the fun variable is the function to minimize, x0 is the initial guess, xmin is the location of the minimum found, and fval is the value of the function at the minimum found. In the second example, lb and ub are the lower and upper bounds on the variables, respectively, and nonlcon is a function handle to the nonlinear constraint.

related categories

gistlibby LogSnag