Minimize a function using Newton's Method
Show older comments
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
xlabel x; ylabel y; zlabel z;
title('Newton Method');
hold off
grid on;
Answers (1)
Matt J
on 13 Apr 2022
0 votes
Perhaps you should be using the method that you accepted yesterday,
6 Comments
Shikhar Singh
on 13 Apr 2022
Shikhar Singh
on 13 Apr 2022
Shikhar Singh
on 13 Apr 2022
Matt J
on 13 Apr 2022
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.
Categories
Find more on Systems of Nonlinear Equations 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!