How do I plot contours of a symbolic function at a specific heigh?
2 次查看(过去 30 天)
显示 更早的评论
So I'm trying to implement Newton's method for optimization and I don't know how to plot the contour at each step vector. I think I have to use ezplot but I keep on getting errors when I try to specify the contour height. Attached is my code. Thank you!
EDIT: I realized my arrows dont touch the points either.
function myNewton(x01,x02)
syms x1 x2
f=symfun((2-x1).^2+200*(x2-x1.^2).^2,[x1,x2]);
f1p=gradient(f,[x1,x2]);
f2p=hessian(f,[x1,x2]);
i=1;
% x01=45
% x02=33
x(1,1)=x01;
x(2,1)=x02;
ax1=linspace(0,20,100);
ax2=linspace(0,20,100);
[X1,X2]=meshgrid(ax1,ax2);
figure
z1=double(f(X1,X2))
contour(X1,X2,z1,[double(f(x01,x02)),double(f(x01,x02))])
axis([0 20 0 20])
hold on
plot(x01,x02,'*')
hold on
while norm(f1p(x(1,i),x(2,i)))>=10^-5
delx=-inv(f2p(x(1,i),x(2,i)))*f1p(x(1,i),x(2,i));
x(1,i+1)=x(1,i)+delx(1,1);
x(2,i+1)=x(2,i)+delx(2,1);
ax1=linspace(0,.1,100);
ax2=linspace(0,.1,100);
[X1,X2]=meshgrid(ax1,ax2);
z=double(f(X1,X2));
contour(X1,X2,z,[double(f(x(1,i+1),x(2,i+1))),double(f(x(1,i+1),x(2,i+1)))])
hold on
quiver(x(1,i),x(2,i),delx(1,1),delx(2,1))
hold on
i=i+1;
end
fprintf('%d %d %d',x(1,i),x(2,i),i)
1 个评论
Karan Gill
2018-2-12
Why do you need symbolic here? Is this possible with just numeric calculations? Also, for contours of sym expressions, use fcontour in 16a+ and ezcontour pre-16a.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Contour Plots 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!