How to do a surface plot with tangent plane?

18 views (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 26 May 2020
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 Comments
Alex Vasin
Alex Vasin on 26 May 2020
Is there a way to center the plot on the point (2,0)?
Star Strider
Star Strider on 26 May 2020
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Numerical Integration and Differential Equations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!