为什么我们需要一个矩阵来在 MATLAB 中绘制 3D 图形?

Why do we need a matrix to plot 3D graphs in MATLAB?

我在学习 MATLAB 时发现了这段用于绘制 3d 图的代码

x=-8:0.1:8
y=x
[X,Y]=meshgrid(x,y)
R=sqrt(X.^2+Y.^2)+eps
Z=sin(R)./R
mesh(x,y,Z,'-')

meshgrid函数的使用感到困惑,我决定尽量避免使用它,而是写成

x=-8:0.1:8
y=x
r=sqrt(x.^2+y.^2)+eps
z=sin(r)./r
mesh(x,y,z)

令我惊讶的是,它显示了一个错误

Z must be a matrix, not a scalar or vector

现在,据我所知,要绘制 3d 图,您只需要根据给定的值相应地标记点 (x,y,z)(对于 2d,这就是它的作用)。为此,它只需要 xyz 的值列表。那么,将 z 作为列表到底有什么问题呢?我想要一个详细的答案。

如果您查看找到该示例的 documentation page,则会给出用法: 强调我的

mesh(X,Y,Z) creates a mesh plot, which is a three-dimensional surface that has solid edge colors and no face colors. The function plots the values in matrix Z as heights above a grid in the x-y plane defined by X and Y. The edge colors vary according to the heights specified by Z.

你提到的例子是这样的:

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z)

meshgrid() 的文档说:

[X,Y] = meshgrid(x) is the same as [X,Y] = meshgrid(x,x), returning square grid coordinates with grid size length(x)-by-length(x).

好的,meshgrid(x, x)在做什么?

[X,Y] = meshgrid(x,y) returns 2-D grid coordinates based on the coordinates contained in vectors x and y. X is a matrix where each row is a copy of x, and Y is a matrix where each column is a copy of y. The grid represented by the coordinates X and Y has length(y) rows and length(x) columns.

这是不言自明的,对吧?例如,当您执行 [X, Y] = meshgrid(-8:2:8) 时,您会得到: 我降低了点的密度以帮助阐明正在发生的事情

X =

  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8
  -8  -6  -4  -2   0   2   4   6   8

Y =

  -8  -8  -8  -8  -8  -8  -8  -8  -8
  -6  -6  -6  -6  -6  -6  -6  -6  -6
  -4  -4  -4  -4  -4  -4  -4  -4  -4
  -2  -2  -2  -2  -2  -2  -2  -2  -2
   0   0   0   0   0   0   0   0   0
   2   2   2   2   2   2   2   2   2
   4   4   4   4   4   4   4   4   4
   6   6   6   6   6   6   6   6   6
   8   8   8   8   8   8   8   8   8

如果你为所有 ij 绘制 x = X(i, j)y = Y(i, j) 给出的每个点,你会得到这样的东西:

当您执行下一行时:

R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R) ./ R;

你正在做矩阵数学运算,RZ 就像 XY 一样是矩阵。元素 Z(i, j) 为您提供 z 轴在 x = X(i, j)y = Y(i, j).

处的值

但是,当您 运行 您的 代码时,xyz 是向量。如果你绘制所有成对的 xy(我再次降低了点的密度),你会得到红点——一条对角线,而不是你实际需要的网格。

mesh() 需要 你的点在网格上(因为它就是这样做的——创建一个 mesh 图).您的代码仅提供对角线 x = y.

上点的 z

绘制矩阵给出曲面/网格图:

如果您只想要 3D 线图,请查看 plot3() 函数。

plot3(x, y, z) 给出: