### 3个变量的函数的轮廓图

2407 观看

1回复

16488 作者的声誉

``````[x,y]= meshgrid(-10:10, -10:10);
contour(x,y, (x.^2)+(y.^2));
``````

### 回应 (1)

2

1784 作者的声誉

matlab函数可以满足`isosurface`您的要求。但是，您也可以使用其他替代方法来获得所需的结果，例如使用`surf`。我将介绍这两种方法。

## 方法1：使用 `isosurface`

`k`反复给出不同的值并查看与这些值关联的轮廓非常有趣。

``````% Value for x, y and z domain.
a = 10;

% Domain for x ,y and z.
x = linspace(-a,a);
y = linspace(-a,a);
z = linspace(-a,a);

% Generate a 3D mesh with x, y and z.
[x,y,z] = meshgrid(x,y,z);

% Evaluate function (3D volume of data).
f = x.^2 + y.^2 + z.^2;

% Do contours from k = 0 to k = 100 in steps of 1 unit.
for k = 0:100
% Draw the contour that matches k.
p = patch(isosurface(x,y,z,f,k));
isonormals(x,y,z,f,p)
p.FaceColor = 'red';
p.EdgeColor = 'none';

title(sprintf('Contours of f(x,y,z) = x^2 + y^2 + z^2\nwith f(x,y,z) = k = %d',k));
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
axis equal;
grid on;
box on;
axis([-10 10 -10 10 -10 10]);
camlight left;
lighting phong;

% Update figure.
drawnow;

% Clear axes.
cla;
end
``````

## 方法2：使用 `surf`

``````% Do contours from k = 0 to k = 100 in steps of 1 unit.
for k = 0:100
% Find the value where: k - x^2 - y^2 = 0
a = sqrt(k);

% Domain for x and y.
x = linspace(-a,a);
y = linspace(-a,a);
[x,y] = meshgrid(x, y);

% Isolate z in terms of k, x and y.
z = sqrt(k-x.^2-y.^2);

% Find complex entries in z.
i = find(real(z)~=z);

% Replace complex entries with NaN.
z(i) = NaN;

% Draw upper hemisphere of surface.
surf(x,y,z,'FaceColor','red','EdgeColor','none');
hold on;
% Draw lower hemisphere of surface.
surf(x,y,-z,'FaceColor','red','EdgeColor','none');

title(sprintf('Contours of f(x,y,z) = x^2 + y^2 + z^2\nwith f(x,y,z) = k = %d',k));
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
axis equal;
grid on;
box on;
axis([-10 10 -10 10 -10 10]);
camlight left;
lighting phong;

% Update figure.
drawnow;
hold off;
end
``````