MATLAB: How to do a surface plot with tangent plane

math

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.

Best Answer

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*')
.