MATLAB: Error – User supplied objective function must return a scalar value

fminunc

Hello! I have a problem. I want to minimize function? but I have error – User supplied objective function must return a scalar value. Please, help me! This is myfun.m
function y = myfun(x)
y=('abs(x(1)+5)+(x(2)-2)^2+(x(3)-3)^2+(x(4)-4)^2');
options=optimset('MaxIter',10000);
options.MaxFunEvals = 15000000000;
options.Display = 'iter';
options.TolFun=1e-1000000;
options.TolX=0.000000001;
x0=[2,4,8,16];
tic
[xopt,yopt] = fminunc(@myfun,x0,options);
k=length(xopt);
for j=1:k
x(i,j)=xopt(j);
end
y(i)=yopt;
t(i) = toc;

Best Answer

I can't be sure from your post where myfun begins and ends, but the quotation marks are definitely messing you up. I think you might mean the following
function y = myfun(x)
y = abs(x(1)+5)+(x(2)-2)^2+(x(3)-3)^2+(x(4)-4)^2;
end
Regardless, it will be problematic to use fminunc on this particular function. The function myfun() is not differentiable in the term abs(x(1)+5). I assume you also know that the function is trivial to minimize by hand.