Why does fmincon give me wrong results?
5 views (last 30 days)
Show older comments
I want to solve the problem for a given with neighborhood with fmincon. So I used
[dp,~] = fmincon(@(p) -fun([x,p]),0,[],[],[],[],[],[],@constr);
and for some points x it gives wrong results as you can see in the plot.
Does anyone know why this happens and how to avoid it?
2 Comments
Dyuman Joshi
on 29 Dec 2023
Could you please share the code you wrote for solving the optimization problem?
Accepted Answer
Matt J
on 29 Dec 2023
Edited: Matt J
on 29 Dec 2023
The problem has a very simple analytical solution. Why use fmincon at all?
[fval,i]=max(2*(x-1)^4, 2*(x+1)^4);
dx=2*i-3;
In any case, it appears that fmincon fails because your initial guess is too close to the first order stationary point at x=0.
x = 0;
objFun = @(dx) -2*(x+dx).^4;
dx0 = 0.01;
nonlcon = @(dx) deal(norm(dx)^2 - 1, []); %Make constraints differentiable
options = optimoptions('fmincon', 'Algorithm', 'sqp');
[dx,fval] = fmincon(objFun,dx0,[],[],[],[],[],[],nonlcon,options)
5 Comments
Matt J
on 29 Dec 2023
I don't know what your real problem looks like. Basically, avoid an initial guess that is too near any local solutions, be they minima, maxima, or inflection points.
More Answers (1)
Hassaan
on 29 Dec 2023
A basic structure of how you could set up your optimization problem in MATLAB:
% Define the objective function, which should be negated for maximization
objFun = @(p) -yourFunctionToMaximize(p);
% Define the initial guess
x0 = yourInitialGuess; % This should be within the neighborhood N
% Define the nonlinear constraint function for the neighborhood N
nonlcon = @(x) deal([], norm(x) - 1); % An empty matrix [] for inequality constraints and norm(x) - 1 for equality
% Set options for fmincon, you can try different algorithms if needed
options = optimoptions('fmincon', 'Algorithm', 'sqp', 'Display', 'iter');
% Run the optimization
[x, fval] = fmincon(objFun, x0, [], [], [], [], [], [], nonlcon, options);
Make sure to replace yourFunctionToMaximize with the actual function you're maximizing and yourInitialGuess with a suitable starting point for the algorithm. The nonlcon function is defined to enforce the neighborhood constraint. The deal function is used to return empty inequality constraints and the equality constraint for the neighborhood definition.
------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!