问题描述
假设我有一个函数 f=@(x) -1/x^2。我需要找到 [1,2] 之间的最大值。 所以答案是 1 因为如果 x=1 abs(-1/x^2) 的最大值
是否有 matlab/octave 内置功能,可以接受一个函数、区间并返回一个数字?
解决方法
您的问题是非线性规划问题的一个实例。
在基本倍频程中,您可以使用 sqp
函数:
https://octave.org/doc/v6.2.0/Nonlinear-Programming.html#Nonlinear-Programming
示例:
f = @(x) -1 ./ (x .^ 2);
Min = sqp( 1.5,% Initial guess. I chose middle of proposed range
f,% The function to be minimized
[],% Function representing equality constraint. Not used here.
[],% Function representing inequality constraint. Not used here.
1,% Lower bound of 1 for x
2 % Upper bound of 2 for x
)
% output: Min = 1
另外还有来自 optim 包/工具箱的 fmincon
(分别在 octave/matlab 中),其工作方式类似。如果您特别关注八度音程/matlab 的互通性,这可能是更好的选择。