MATLAB - 3D 繪圖



MATLAB 提供了強大的工具來建立三維視覺化,允許使用者在 3D 空間中表示和探索資料。3D 繪圖對於視覺化複雜資料至關重要,例如曲面、體積和多維資料集。

3D 繪圖型別

  • 曲面圖 - 這些使用表示變數之間關係的曲面來視覺化兩個變數的函式。
  • 網格圖 - 網格圖顯示線框曲面,對於在網格上視覺化兩個變數的函式很有用。
  • 散點圖 - 在 3D 中,散點圖以三個維度表示單個數據點,通常使用不同的符號或顏色來表示不同的屬性。

語法

plot3(X,Y,Z)
plot3(X,Y,Z,LineSpec)
plot3(X1,Y1,Z1,...,Xn,Yn,Zn)
plot3(X1,Y1,Z1,LineSpec1,...,Xn,Yn,Zn,LineSpecn)

plot3(X,Y,Z) - 此方法負責在 3D 空間中繪製 X、Y 和 Z 的座標。

  • 要透過線段繪製連線的座標,請確保 X、Y 和 Z 是長度相同的向量。
  • 要在單個軸集上視覺化多個座標集,請將 X、Y 或 Z 中的至少一個指定為矩陣,而其餘的保持為向量。

plot3(X,Y,Z,LineSpec) - 此方法繪製具有指定線型、標記和顏色的 3D 圖。

plot3(X1,Y1,Z1,...,Xn,Yn,Zn) - 此方法有助於在同一組軸上繪製多組座標。

plot3(X1,Y1,Z1,LineSpec1,...,Xn,Yn,Zn,LineSpecn) - plot3 函式允許為各個 XYZ 三元組分配不同的線型、標記和顏色。可以為某些三元組指定 LineSpec,而為其他三元組省略。例如,使用 plot3(X1,Y1,Z1,'o',X2,Y2,Z2) 將標記分配給第一個三元組,但不分配給第二個三元組。

根據上面討論的語法,讓我們嘗試一些示例來繪製 3D 圖。

示例 1

螺旋線可以透過 x、y 和 z 的引數方程生成。螺旋線在柱座標系中的通用方程為 -

以下是一個將使用 plot3(X,Y,Z) 繪製 3D 螺旋線的示例 -

x=r.cos(t)

y=r.sin(t)

z=h.t

其中 r 是螺旋線的半徑,t 是引數,h 表示螺距或螺旋線在一圈完整旋轉中垂直移動的距離。

% Parameters
r = 1;  % Radius
h = 1;  % Pitch
t = 0:0.1:10*pi;  % Parameter range

% Parametric equations for x, y, z
x = r * cos(t);
y = r * sin(t);
z = h * t;

% Plotting the helix
plot3(x, y, z);

當您在 matlab 命令視窗中執行相同操作時,輸出為 -

draw 3d helix

示例 2

使用上述相同示例,讓我們為 3D 繪圖使用圓形標記

% Parameters
r = 1;  % Radius
h = 1;  % Pitch
t = 0:0.1:10*pi;  % Parameter range

% Parametric equations for x, y, z
x = r * cos(t);
y = r * sin(t);
z = h * t;

% Plotting the helix
plot3(x, y, z, 'o');

當您在 matlab 命令視窗中執行相同操作時,輸出為 -

circular markers

示例 3

讓我們使用此 plot3(X1,Y1,Z1,...,Xn,Yn,Zn) 繪製 3D 的多條線。

% Define parameters and range
t = 0:0.1:10*pi;  % Parameter range

% Line 1
r1 = 1;  % Radius of the first helix
h1 = 1;  % Pitch of the first helix
x1 = r1 * cos(t);
y1 = r1 * sin(t);
z1 = h1 * t;

% Line 2
r2 = 0.5;  % Radius of the second helix
h2 = 2;    % Pitch of the second helix
x2 = r2 * cos(t);
y2 = r2 * sin(t);
z2 = h2 * t;

% Plotting multiple lines
plot3(x1, y1, z1,x2, y2, z2);

當您在 matlab 中執行相同操作時,輸出如下 -

plot multiple lines

示例 4

plot3(X1,Y1,Z1,LineSpec1,...,Xn,Yn,Zn,LineSpecn) ,讓我們為多條線 3D 繪圖指定線型。

% Define parameters and range
t = 0:0.1:10*pi;  % Parameter range

% Line 1
r1 = 1;  % Radius of the first helix
h1 = 1;  % Pitch of the first helix
x1 = r1 * cos(t);
y1 = r1 * sin(t);
z1 = h1 * t;

% Line 2
r2 = 0.5;  % Radius of the second helix
h2 = 2;    % Pitch of the second helix
x2 = r2 * cos(t);
y2 = r2 * sin(t);
z2 = h2 * t;

% Plotting multiple lines
plot3(x1, y1, z1,'o',x2, y2, z2,'+');

對於第一條線,我們使用了圓形 (o) 標記,對於第二條線,我們使用了加號 (+) 線型。

程式碼執行後的輸出如下 -

multiple line 3d

示例 5

在這個示例中,我們將看到標記和線型的自定義。

% Parameters
r = 1;  % Radius
h = 1;  % Pitch
t = 0:0.1:10*pi;  % Parameter range

% Parametric equations for x, y, z
x = r * cos(t);
y = r * sin(t);
z = h * t;

% Plotting the helix
plot3(x, y, z,'-o','Color','b','MarkerSize',10,'MarkerFaceColor','#CFCFCF')

當您在 matlab 命令視窗中執行相同操作時,輸出為 -

Marker Size
廣告