Opening the book…
The fminsearch function is similar to fzero, which we saw in Chapter 7. Recall that fzero takes a function handle and an initial guess, and it returns a root of the function. As an example, to find a root of the function
function res = error_func(x)
res = x^2 - 2;
end
we can call fzero like this:
>> x = fzero(@error_func, 1)
ans = 1.4142
The result is near the square root of 2. Let’s call fminsearch with the same function:
>> x = fminsearch(@error_func, 1)
x = -8.8818e-16
The result is close to 0, which is where this function is minimized. Optionally, fminsearch returns two values:
>> [x, fval] = fminsearch(@error_func, 1)
x = -8.8818e-16
fval = -2
The x is the location of the minimum, and fval is the value of the function evaluated at x.
If we want to find the maximum of a function, rather than the minimum, we can still use fminsearch by writing a short function that negates the function we want to maximize. In the baseball example, the function we want to maximize is baseball_range; we can wrap it in another function like this:
function res = min_func(angle)
res = -baseball_range(angle);
end
And then we call fminsearch like this:
>> [x, fval] = fminsearch(@min_func, pi/4)
x = 0.6921
fval = -131.5851
The optimal launch angle for the baseball is 0.69 rad; launched at that angle, the ball travels almost 132 m.
If you’re curious about how fminsearch works, see “How fminsearch Works” on page 15.3.
This page titled 13.4: fminsearch was last modified on Thu, 17 Nov 2022 18:20:14 GMT and is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.
The book could not be loaded just now.