How to do a surface plot with tangent plane?

9 次查看(过去 30 天)
f = @(x,y) x.^2 + y.^2;
[xx,yy] = meshgrid(-5:0.25:5);
[fx,fy] = gradient(f(xx,yy),0.25);
x0 = 1;
y0 = 2;
t = (xx == x0) & (yy == y0);
indt = find(t);
fx0 = fx(indt);
fy0 = fy(indt);
z = @(x,y) f(x0,y0) + fx0*(x-x0) + fy0*(y-y0);
surf(xx,yy,f(xx,yy),'EdgeAlpha',0.7,'FaceAlpha',0.9)
hold on
surf(xx,yy,z(xx,yy))
plot3(1,2,f(1,2),'r*')
The function is z=f(x,y)=(x.^2*y + cos(x*y))/(x.^2 + y.^2). The point is (2,0), and the equation of the tangent is z=-(x/4)+y+(3/4). I don't know how to make it work, any help would be appreciated. Thanks.

采纳的回答

Star Strider
Star Strider 2020-5-26
I believe the problem is that you need to vectorise the function, using element-wise operations in the multiplications and division as well as the exponentiations (that you already did). Otherwise, all that you need to do is to specify ‘x0’ and ‘y0’ as the values you want.
Try this:
f = @(x,y) (x.^2.*y + cos(x.*y))./(x.^2 + y.^2);
[xx,yy] = meshgrid(-5:0.25:5);
[fx,fy] = gradient(f(xx,yy),0.25);
x0 = 2;
y0 = 0;
t = (xx == x0) & (yy == y0);
indt = find(t);
fx0 = fx(indt);
fy0 = fy(indt);
z = @(x,y) f(x0,y0) + fx0*(x-x0) + fy0*(y-y0);
surf(xx,yy,f(xx,yy),'EdgeAlpha',0.7,'FaceAlpha',0.9)
hold on
surf(xx,yy,z(xx,yy))
plot3(1,2,f(1,2),'r*')
.
  3 个评论
Alex Vasin
Alex Vasin 2020-5-26
Is there a way to center the plot on the point (2,0)?
Star Strider
Star Strider 2020-5-26
I didn’t catch the last line.
It’s straightforward to adapt it to any (x0,y0):
plot3(1,2,f(x0,y0),'r*')
however to see it, the plot view must be set differently:
view(-140,20)
the complete code now being:
f = @(x,y) (x.^2.*y + cos(x.*y))./(x.^2 + y.^2);
[xx,yy] = meshgrid(-5:0.25:5);
[fx,fy] = gradient(f(xx,yy),0.25);
x0 = 2;
y0 = 0;
t = (xx == x0) & (yy == y0);
indt = find(t);
fx0 = fx(indt);
fy0 = fy(indt);
z = @(x,y) f(x0,y0) + fx0*(x-x0) + fy0*(y-y0);
surf(xx,yy,f(xx,yy),'EdgeAlpha',0.7,'FaceAlpha',0.9)
hold on
surf(xx,yy,z(xx,yy))
plot3(1,2,f(x0,y0),'r*')
view(-140,20)
Unfortunately, unlike in the example code given in the documentation, the plane is not tangent to your function at the desired point. The tangent and the curve do not even intersect at that point.
It’s not my code, however I’ll look through it later to see if I can find out what the problem is, and fix it if possible, since it’s interesting.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by