How to find the minimum using Newton method (matlab)
조회 수: 8 (최근 30일)
이전 댓글 표시
I am given this function: f(x, y) = 1(x − 1)2 + 1(10(y − x2))2 + 1y2 and I tried to write the code below to find the minimum but it doesn't seem to work.
syms a;
syms b;
g=gradient(vrosenbrock(a,b));
x=-1;
y=-1;
z=0;
i=1;
H=hessian(vrosenbrock(a,b));
while norm(subs(g,[a,b],[x,y])) > 10e-3
z=[x,y]-((subs(inv(H),[a,b],[x,y]))*((subs(g,[a,b],[x,y])))).' ;
x=z(1); y=z(2);
i=i+1;
end
[x y]
And as function I've saved this already: function z = vrosenbrock(x,y)
FUN = 1;
if FUN == 1
z = 0.5*(10*(y - x.^2)).^2 + 0.5*(1-x).^2 + 0.5*y.^2;
elseif FUN == 2
z = (10*(y - x.^2)).^2 + (1-x).^2;
end
end
댓글 수: 0
답변 (1개)
Ayush Modi
2024년 8월 27일
Hi Nikoo,
I understand you are trying to implement the Newton's method for finding the minimum of the given function.
Here is the example code to get you started:
syms a b;
% Define the function - taking example function
vrosenbrock = @(x, y) 0.5*(10*(y - x.^2)).^2 + 0.5*(1-x).^2 + 0.5*y.^2;
% Compute the gradient and Hessian
g = gradient(vrosenbrock(a, b), [a, b]);
H = hessian(vrosenbrock(a, b), [a, b]);
% Initial guess
x = -1;
y = -1;
% Iteration counter
i = 1;
while norm(double(subs(g, [a, b], [x, y]))) > 1e-3
grad_val = double(subs(g, [a, b], [x, y]));
hess_val = double(subs(H, [a, b], [x, y]));
z = [x; y] - hess_val \ grad_val;;
x = z(1);
y = z(2);
i = i + 1;
end
disp(['Minimum found at x = ', num2str(x), ', y = ', num2str(y)]);
Refer to the following MathWorks documentation for more information on (\) i.e. backslash operator in MATLAB:
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!