MATLAB: Error in fmincon. How to write “x0” as an array. Optimization

fminconnonlinearnumerical integrationoptimizationOptimization Toolbox

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

Best Answer

You need to return your ‘y’ variables as a vector, not individual arguments.
Thsi should work in your fmincon call:
objF = matlabFunction(obj, 'Vars',{[y]}) % function_handle
producing:
objF =
function_handle with value:
@(in1)in1(:,1)-in1(:,2).*2.0-in1(:,3)-in1(:,4)+in1(:,5).*2.0
Note that ‘in1’ is a row vector, so your specifying ‘x0’ as a row vector is correct.
See the matlabFunction documentation section on 'Vars' (link) and Specify Input Arguments for Generated Function (link) for an extended discussion on its use.