Minimize a function using Newton's Method

조회 수: 4 (최근 30일)
Shikhar Singh
Shikhar Singh 2022년 4월 13일
댓글: Matt J 2022년 4월 13일
I am trying to minimise the function stated below using Newton's method, however I am not able to display a plot which illustrates points as they iterate down towards the minimum:
% Minimise z =(3-X).^2 + 30*((Y-(X.^2)).^2) with a starting point of x=y=0
% My implementation:
X = -4:0.01:4; % Declare range of x values
[X,Y] = meshgrid(X); % return 2-D grid coordinates
f =(3-X).^2 + 30*((Y-(X.^2)).^2); % Initiallize function for plotting
surf(X,Y,f,'FaceColor','y','FaceAlpha',0.3,'EdgeColor','none'); % Plot function
syms X Y;
f =(3-X).^2 + 30*((Y-(X.^2)).^2);
x(1) = 0; % Initial value of x
y(1) = 0;% Initial value of y
df_dx = diff(f, X);
df_dy = diff(f, Y);
J = [subs(df_dx,[X,Y], [x(1),y(1)]) subs(df_dy, [X,Y], [x(1),y(1)])]; % Gradient
ddf_ddx = diff(df_dx,X);
ddf_ddy = diff(df_dy,Y);
ddf_dxdy = diff(df_dx,Y);
ddf_ddx_1 = subs(ddf_ddx, [X,Y], [x(1),y(1)]);
ddf_ddy_1 = subs(ddf_ddy, [X,Y], [x(1),y(1)]);
ddf_dxdy_1 = subs(ddf_dxdy, [X,Y], [x(1),y(1)]);
H = [ddf_ddx_1, ddf_dxdy_1; ddf_dxdy_1, ddf_ddy_1]; % Hessian
B = inv(H);
for i = 1:60
A = [x(i),y(i)]';
x(i+1) = A(1)-B(1,:)*J';
y(i+1) = A(2)-B(2,:)*J';
i = i+1;
J = [subs(df_dx,[X,Y], [x(i),y(i)]) subs(df_dy, [X,Y], [x(i),y(i)])]; % Update Jacobian
ddf_ddx_1 = subs(ddf_ddx, [X,Y], [x(i),y(i)]);
ddf_ddy_1 = subs(ddf_ddy, [X,Y], [x(i),y(i)]);
ddf_dxdy_1 = subs(ddf_dxdy, [X,Y], [x(i),y(i)]);
H = [ddf_ddx_1, ddf_dxdy_1; ddf_dxdy_1, ddf_ddy_1]; % Update Hessian
B = inv(H); % New Search Direction
end
% Plot:
hold on;
plot3(x,y,f,'o','Markersize',3,'Color','red'); % Illustrate descent
Error using plot3
Data must be numeric, datetime, duration or an array convertible to double.
xlabel x; ylabel y; zlabel z;
title('Newton Method');
hold off
grid on;

답변 (1개)

Matt J
Matt J 2022년 4월 13일
  댓글 수: 6
Shikhar Singh
Shikhar Singh 2022년 4월 13일
I have updated the code above with plot3 implemented.
Matt J
Matt J 2022년 4월 13일
You cannot pass symbolic variables (like f) to plot3. In your previous post, you computed a sequence of z values that you fed to plot3,
z(i+1) = ((3-x(i+1)).^2) + (30.*(y(i+1)-(x(i+1).^2)).^2);
You have not done a similar thing here.

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

카테고리

Help CenterFile Exchange에서 Systems of Nonlinear Equations에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by