如何在matlab中绘制3D垂直平面

时间:2018-04-03 20:19:49

标签: matlab plot 3d

我有一个函数f(x,y),这样

f(x,y)= h(x,y),如果x-y <-0.5

如果-0.5 <= x-y <0

f(x,y)= k(x,y),如果x-y> = 0

我想在3D空间(x,y,z)中绘制它,其中z代表f(x,y)的值。另外,我还想生成像x-y = -0.5,x-y = 0这样的垂直平面,并将它们绘制在相同的3D空间中,这样我就可以看到f(x,y)在(x,y)中不同区域的变化情况。如何在matlab中的一个3D图中一起绘制这些图?

1 个答案:

答案 0 :(得分:1)

首先,您需要生成xy点的网格,以评估您的函数f(x,y)。您可以使用meshgrid执行此操作。例如,对于xy,这将为-1到1创建201 x 201点网格:

[x, y] = meshgrid(-1:0.01:1);

现在,您可以使用z的结果填充矩阵f(x,y),使用logical indexing评估网格点不同子集的每个部分:

z = 5.*x+4.*y;                       % Use g(x,y) as default fill value
index = ((x-y) < -0.5);              % Logical index of grid points for h(x,y)
z(index) = x(index).^2+y(index).^2;  % Evaluate h(x,y) at index points
index = ((x-y) >= 0);                % Logical index of grid points for k(x,y)
z(index) = x(index).*y(index);       % Evaluate k(x,y) at index points

现在,您可以使用surf绘制z

surf(x, y, z, 'EdgeColor', 'none');  % Plots surface without edge lines

然后,您可以为平面生成角坐标,并使用patch绘制它们(有关详细信息,请参阅this question中链接的a comment from bla)。这是生成它们的一种方法(将它们设置为具有一些Alpha透明度的红色):

xPlane = [-1 1 1 -1];      % X coordinates of plane corners, ordered around the plane
yPlane1 = xPlane+0.5;      % Corresponding y coordinates for plane 1
yPlane2 = xPlane;          % Corresponding y coordinates for plane 2
zPlane = [-10 -10 10 10];  % Z coordinates of plane corners
hold on;                   % Add to existing plot
patch(xPlane, yPlane1, zPlane, 'r', 'FaceAlpha', 0.5);  % Plot plane 1
patch(xPlane, yPlane2, zPlane, 'r', 'FaceAlpha', 0.5);  % Plot plane 2

这是由此产生的情节:

enter image description here