Reputation: 133
I'm trying to write an M-file that finds the max/min of a function, given a certain range.
Let's say I have defined an equation in the command window like so:
> y = @(x) -1*x^2 + 3
y =
function_handle with value:
@(x)-1*x^2+3
And let's say my desired range is from -3 to 3... So I would start my M-file with
function fminmax = input(f, lowerbound, upperbound)
but then what would I use? I've been googling for a while and I cant find anything helpful. Please help!
Upvotes: 0
Views: 4191
Reputation: 46
You could use the already existing function x = fminbnd(fun, x1, x2)
which gives you the min for a function handle fun
in the range of x1
and x2
. To get the max you could just use the negative of your function handle.
Your function could look like this:
function [min, max] = fminmax(f, lowerbound, upperbound)
min = fminbnd(f, lowerbound, upperbound);
max = fminbnd(@(x) -f(x), lowerbound, upperbound);
end
Upvotes: 3