Matlab 使用 fminsearch 优化一个数字区间

Matlab use fminsearch to optimize a interval of numbers

在 Matlab 中,我想使用 fminsearch 优化给定目标函数 fun 的数字区间以最小化。整数可以从1到30中选择,目前整数个数固定为5个。假设步长为1。它会优化很多向量如:

[1 2 3 4 5]
[2 3 4 5 6]
[7 8 9 10 11]
[12 13 14 15 16]

在长运行中,我可能还会尝试优化向量中的步长和整数个数。

我想知道如何使用 fminsearch 正确实现这一点或者使用工具箱中的其他功能?任何建议将不胜感激。

首先如documentation, fminsearch can only find minimum of unconstrained functions. fminbnd, on the other hand, can handle the bound constraint, however, non of these functions are meant to solve discrete functions. So you probably want to think of other options, ga所述

尽管 fminsearch 不处理约束,但您仍然可以使用它来解决您的优化问题,但需要付出一些不必要的额外迭代代价。在这个答案中,我假设有一个 fun 函数将特定范围内的间隔作为其参数,而 objective 是找到最小化它的间隔。

由于区间的步长和长度是固定的,所以问题是单变量的,我们只需要找到它的起点即可。我们可以使用 floor 将连续问题转换为离散问题。为了覆盖边界约束,我们可以检查区间的可行性,并检查 return Inf 不可行的区间。那将是这样的:

%% initialization of problem parameters
minval = 1;
maxval = 30;
step = 1;
count = 5;
%% the objective function
fun = @(interval) sum((interval-5).^2, 2);
%% a function that generates an interval from its initial value
getinterval = @(start) floor(start) + (0:(count-1)) * step;
%% a modified objective function that handles constraints
objective = @(start) f(start, fun, getinterval, minval, maxval);
%% finding the interval that minimizes the objective function
y = fminsearch(objective, (minval+maxval)/2);
best = getinterval(y);
eval = fun(best);
disp(best)
disp(eval)

其中 f 函数是:

function y = f(start, fun, getinterval, minval, maxval)
interval = getinterval(start);
if (min(interval) < minval) || (max(interval) > maxval)
    y = Inf;
else
    y = fun(interval);
end
end