Matlab使用fminsearch优化数字间隔 [英] Matlab use fminsearch to optimize a interval of numbers
问题描述
在Matlab中,我想使用fminsearch来优化给定对象函数fun
的数字间隔.整数可以从1到30中选择,并且目前整数数量固定为5.假设步长为1.它将优化许多矢量,例如:
In Matlab I want to use fminsearch to optimize a interval of numbers given a object function fun
to minimize. The integer numbers can be selected from 1 to 30, and the number of integers is fixed to 5 for now. Assume the step size is 1. It will optimize many vectors such as:
[1 2 3 4 5]
[2 3 4 5 6]
[7 8 9 10 11]
[12 13 14 15 16]
从长远来看,我可能还会尝试优化向量的步长和整数数量.
In the long run, I may also try to optimize the step size and number of integers in the vector.
我想知道如何使用fminsearch正确实现这一目标,或者可能使用工具箱中的其他功能?任何建议将不胜感激.
I want to know how to use fminsearch to properly realize this or maybe use other functions in the toolbox? Any suggestion will be appreciated.
推荐答案
首先,如文档,fminsearch
只能找到最少的不受约束的函数.另一方面, fminbnd
可以处理绑定约束但是,这些功能均不能解决离散功能.因此,您可能想考虑其他选项,例如ga
.
First of all, as stated in 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
for example.
尽管fminsearch
不能处理约束,但是您仍然可以使用它来解决您的优化问题,但需要花费一些不必要的额外迭代.在这个答案中,我假设有一个fun
函数,该函数以一个特定范围内的间隔作为参数,目的是找到使该间隔最小的函数.
Despite the fact that fminsearch
does not handle constraints, but still you can use it to solve your optimization problem with cost of some unnecessary extra iterations. In this answer I assume that there is a fun
function that takes an interval from a specific range as its argument and the objective is to find the interval that minimizes it.
由于间隔具有固定的步长和长度,因此问题是单变量的,我们只需要找到其起点即可.我们可以使用floor
将连续问题转换为离散问题.为了覆盖边界约束,我们可以检查区间的可行性,并为不可行的区间返回Inf
.就像这样:
Since the interval has a fixed step size and length, the problem is single-variable and we only need to find its start point. We can use floor
to convert a continuous problem to a discrete one. To cover the bound constraint we can check for feasibility of intervals and return Inf
for infeasible ones. That will be something like this:
%% 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
这篇关于Matlab使用fminsearch优化数字间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!