maximum of a function in matlab

To find the maximum of a function in MATLAB, you can use the fminbnd function. This function finds the minimum of a function, so to find the maximum, you can simply negate the function and then find the minimum:

main.m
% define function to maximize
fun = @(x) -x^2 + 10*x + 20;

% find maximum
[xmax, ymax] = fminbnd(@(x) -fun(x), 0, 10);

% display results
fprintf('The maximum value of the function is %f at x=%f.\n', -ymax, xmax);
215 chars
9 lines

In this example, we define the function fun to maximize, which is a quadratic with a maximum at x=5. We then use fminbnd to find the minimum of the negated function -fun(x) over the interval [0, 10], which gives us the maximum of fun(x). The output xmax is the value of x that maximizes the function, and -ymax is the value of the maximum.

Note that fminbnd requires that the function be defined on a finite interval, so we provide it with the interval [0, 10] in this example. You may need to adjust the interval depending on the function you are maximizing.

related categories

gistlibby LogSnag