Error in fminunc function
이전 댓글 표시
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.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!