Matlab use fminsearch to optimize a interval of numbers

折月煮酒 提交于 2019-12-12 01:28:36

问题


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.

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.


回答1:


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.

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.

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)

where f function is:

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


来源:https://stackoverflow.com/questions/58984498/matlab-use-fminsearch-to-optimize-a-interval-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!