MATLAB: How to format x0,lb,ub in fmincon with matrix input

fmincon

Hey there,
thanks in advance for reading, and possibly answering, my question.
I encounter a problem using fmincon where I have 40 variables to optimize over, which are organized in 2 vectors, i.e., I have declared x(1), x(2), x(3), …, x(20) and y(1), y(2), …,y(20). While feval(f,[{values for x}],[{values for y}]) and f([{values for x}],[{values for y}]) work fine, I do not seem to be able to initialize fmincon.
Take this (very) simplified example:
f = @(x,y)x(1)+2*x(2)+3*y(1)+4*y(2)
Then
feval(f,[0 0],[0 1])
f([0 0 ],[0 1])
both correctly yield 4.
However, if I attempt to minimize f over x(1),x(2),y(1),y(2), by using, for instance,
fmincon(f,[2 2; 2 2],[],[],[],[],[1 1; 1 1 ],[3 4; 5 6])
this yields
Not enough input arguments.
Error in @(x,y)x(1)+2*x(2)+3*y(1)+4*y(2)
Error in fmincon (line 535)
initVals.f = feval(funfcn{3},X,varargin{:});
Caused by:
Failure in initial objective function evaluation. FMINCON cannot continue
My question is: How do I need to format x0, lb, and ub in fmincon in order to solve the problem?
Many thanks in advance!

Best Answer

There's nothing wrong with the way you've formatted x0,lb,ub. The problem is the way you've written f. It is expected that all the unknowns will be passed to f in one argument, e.g.,
function fval = objective(z)
x=z(:,1);
y=z(:,2);
fval = x(1)+2*x(2)+3*y(1)+4*y(2);
end
and then
fmincon(@objective, [2 2; 2 2],[],[],[],[],[1 1; 1 1 ],[3 4; 5 6])