Error in fminunc function
Show older comments
The problem I'm having is that when I call the fminunc function it doesn't solve the problem because it sayd that the gradient is zero and that it needs two elements, but when I just call the gradient it throws the right one. What am I doing wrong? Please help me :)
This is the script
function [f,grad,hess] = exam_sylvi(x)
f = 2*x(1)+3*x(2)^2+exp(2*x(1)^2+x(2)^2);
if nargout > 1
grad = gradient (f,[x(1),x(2)])
end
if nargout > 2
hess = hessian (f,[x(1),x(2)])
end
end
This is the run
EDU>> grad
grad =
4*x1*exp(2*x1^2 + x2^2) + 2
2*x2*exp(2*x1^2 + x2^2)
EDU>> hess
hess =
[ 4*exp(2*x1^2 + x2^2) + 16*x1^2*exp(2*x1^2 + x2^2), 8*x1*x2*exp(2*x1^2 + x2^2)]
[ 8*x1*x2*exp(2*x1^2 + x2^2), 2*exp(2*x1^2 + x2^2) + 4*x2^2*exp(2*x1^2 + x2^2)]
EDU>> [x,fval,exitflag] = fminsearch(@exam_sylvi,[1,0])
x =
-0.3766 -0.0000
fval =
0.5748
exitflag =
1
EDU>> options = optimoptions('fminunc','Display','iter','Algorithm','quasi-newton','HessUpdate','steepdesc','GradObj','on');
EDU>> [x,fval,exitflag,output] = fminunc(@exam_sylvi,[1,0],options)
grad =
0
Error using fminunc (line 339)
User-defined objective gradient does not have the correct number of elements:
the gradient should have 2 elements.
Accepted Answer
More Answers (0)
Categories
Find more on Conversion 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!