Error in fmincon. How to write "x0" as an array. Optimization
Show older comments
Hi, I am using fmincon to solve a non linear problem and I create a symbolic function (it varies depending on the value n).
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon)
The problem here is that I want to replace an "x0" value as an array in a symbolic function handle of "fun", but I do not know how to write it. I show you a simplification of the problem:
n = 5; % Dimensions
% Function Obj
y = sym('y',[1 n]);
obj = y(1);
for i = 2:(n-1)
obj = obj + y(i+1)-2*y(i); % y(i)
end
obj = obj + y(n); % y(n)
objF = matlabFunction(obj); % function_handle
x0 = zeros(1,n);
% fmincon
[yf, fval] = fmincon(objF, x0, [], [], [], [], [], [], @ nlcon);
As far as I know, I think the problem is that x0 is not being correctly replaced in objF, because I want to replace x0(1) in y1, x0(2) in y2.... and so on.
The error message I obtain is the following one:
Not enough input arguments.
Error in symengine>@(y1,y2,y3,y4,y5)y1-y2.*2.0-y3-y4+y5.*2.0
Error in fmincon (line 546)
initVals.f = feval(funfcn{3},X,varargin{:});
Caused by:
Failure in initial objective function evaluation. FMINCON cannot continue.
I think it is not needed, but I also include a simplified nlcon function (I've tried this last function and works correctly)
function [c ceq] = nlcon(x0)
n= 5;
y = sym('y',[1 n]);
obj = y(1);
for i = 2:(n-1)
obj = obj + y(i+1)-2*y(i); % y(i)
end
obj = obj + y(n); % y(n)
objF = matlabFunction(obj);
% Constrains
c = [];
for i = 1:n
ceq_sym(i) = diff(obj,y(i)); % Gradient
end
ceq = subs(ceq_sym,y,x0);
end
Accepted Answer
More Answers (0)
Categories
Find more on Systems of Nonlinear Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!