MATLAB: Error in using fmincon to minimization

errorfminconminimizationvariableswith function

Hello!
Below I place fragment of my program:
coef123=stats123.beta %Those are 10 coefficients from my 3-variable equetion
xx1=linspace(-1,1);
xx2=linspace(-1,1);
xx3=linspace(-1,1);
[x1,x2,x3]=meshgrid(xx1,xx2,xx3);
z12=coef123(1)+coef123(2)*x1+coef123(3)*x2+coef123(4)*x3+coef123(5)*x1.*x2+coef123(6)*x1.*x3+coef123(7)*x2.*x3+coef123(8)*x1.^2+coef123(9)*x2.^2+coef123(10)*x3.^2;
xstart=[-1;-1;-1];
[x,fval]=fmincon(@(x)wartoscminimalna,xstart,[],[],[],[],[-1,-1,-1],[1,1,1]);
disp(x)
disp(fval)
Additionally I have function:
function f=wartoscminimalna(x1,x2,x3)
global coef123
f=-(coef123(1)+coef123(2)*x1+coef123(3)*x2+coef123(4)*x3+coef123(5)*x1.*x2+coef123(6)*x1.*x3+coef123(7)*x2.*x3+coef123(8)*x1.^2+coef123(9)*x2.^2+coef123(10)*x3.^2);
Can someone tell me why it doesn't work? I have this kind of error:
Undefined function 'coef123' for input arguments of
type 'double'.
Error in wartoscminimalna (line 2)
f=-(coef123(1)+coef123(2)*x1+coef123(3)*x2+coef123(4)*x3+coef123(5)*x1.*x2+coef123(6)*x1.*x3+coef123(7)*x2.*x3+coef123(8)*x1.^2+coef123(9)*x2.^2+coef123(10)*x3.^2);
Error in @(x1,x2,x3)wartoscminimalna
Error in fmincon (line 601)
initVals.f = feval(funfcn{3},X,varargin{:});
Error in programrstool_4D (line 26)
[x,fval]=fmincon(@(x1,x2,x3)wartoscminimalna,xstart,[],[],[],[],[-1,-1,-1],[1,1,1]);
Caused by:
Failure in initial user-supplied objective
function evaluation. FMINCON cannot continue.
Please help me with it.
Mateusz

Best Answer

Your objective should be implemented as follows
function f=wartoscminimalna(x,coeff123)
x1=x(1);
x2=x(2);
x3=x(3);
f=-(coef123(1)+coef123(2)*x1+coef123(3)*x2+coef123(4)*x3+coef123(5)*x1.*x2+coef123(6)*x1.*x3+coef123(7)*x2.*x3+coef123(8)*x1.^2+coef123(9)*x2.^2+coef123(10)*x3.^2);
and then
[x,fval]=fmincon(@(x)wartoscminimalna(x,stats123.beta),xstart,...
[],[],[],[],[-1,-1,-1],[1,1,1]);