Using fminunc with gradient computation

조회 수: 7 (최근 30일)
Quentin Pradelle
Quentin Pradelle 2018년 11월 9일
댓글: Torsten 2018년 11월 9일
Hi, I managed to find the minimizer of a function (see picture), and am now trying to include the computation of the gradient. I can't manage to do it, since the method I use to find the gradient returns an error :
Also I'm wondering why it is useful to compute the gradient in this problem?
<<
<<
>>
>>
% definition of x and y
x=-10:0.1:10;
y=-0.4:0.1:10;
% define a grid (x,y)
[xx,yy]=meshgrid(x,y);
% Evaluation of f(x,y) on this grid
zz = f(xx,yy);
% Quasi Newton
fun = @(x)(x(2) - cos(2*x(1)) - ((x(1).^2)/10)).^2 + exp((x(1).^2 + x(2).^2)/100);
% @ = anonymous function to be used as an argument, x(1) = x, x(2) = y
x0 = [1, 1];
options = optimset('Display','iter', 'GradObj', 'on');
[qN_x, qN_fval] = fminunc(fun, x0, options);
function z = f(x,y)
z = (y - cos(2*x) - ((x.^2)/10)).^2 + exp((x.^2 + y.^2)/100);
end
end

답변 (1개)

Alan Weiss
Alan Weiss 2018년 11월 9일
To include a gradient in the objective function, have the objective return another output, as explained in the documentation.
You seem to have two definitions of your objective function in your script. The first one ( fun = @(x)…) looks good, in that you have just one variable x. Your second, function z = f(x,y)…, is not correct in that it takes two variables. See the link above for how to write scalar objective functions.
When you are done with your objective function it should look like this;
function [z,gz] = myfun(t)
x = t(1);
y = t(2);
z = (y - cos(2*x) - ((x.^2)/10)).^2 + exp((x.^2 + y.^2)/100);
if nargout > 1 % If a gradient is called for
gz(1) = 2*(y - cos(2*x) - ((x.^2)/10)).^2*(2*sin(2*x) - x/5)...
+ x/50*exp((x.^2 + y.^2)/100);
gz(2) = 2*(y - cos(2*x) - ((x.^2)/10)) + y/50*exp((x.^2 + y.^2)/100);
end
I hope that I didn't ruin your homework problem by giving you too explicit an answer.
Alan Weiss
MATLAB mathematical toolbox documentation
  댓글 수: 1
Torsten
Torsten 2018년 11월 9일
gz(1) = 2*(y - cos(2*x) - ((x.^2)/10)).*(2*sin(2*x) - x/5)...
+ x/50.*exp((x.^2 + y.^2)/100);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Spline Postprocessing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by