简体   繁体   中英

Matlab find min/max of function

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM