[英]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. 我正在尝试编写一个找到给定范围的函数的最大值/最小值的M文件。
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 假设我的期望范围是-3到3 ...所以我将以
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
. 你可以使用已经存在的功能,
x = fminbnd(fun, x1, x2)
它为您提供了一个功能手柄分钟fun
的范围x1
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.