跳至內容

MATLAB 程式設計/圖形

來自華夏公益教科書



二維圖形

[編輯 | 編輯原始碼]

繪圖命令在笛卡爾座標系中渲染二維線。

示例

x=0:0.1:2;  % Creates a vector from 0 to 2, spaced by 0.1.
fx=(x+2)./x.^2; % calculates fx based on the values stored in x
plot(x,fx) % Plots 2D graphics of the function fx

Matlab 還允許使用者指定線型。以下示例生成與前一個示例相同的圖形,但使用特定線型繪製函式:黑色線條,每個節點上都有圓形標記

x=linspace(0, 2, 21);  % like the previous example, creates a vector from 0 to 2, spaced by 0.1
fx= arrayfun(@(x) (x+2)/x^2, x); % like the previous example, calculates fx based on the values stored in x
plot(x,fx,'-ok') % Plots the graph of (x, fx) as a black line with circle markers at each point

要在同一個圖形中繪製兩個或多個圖形,只需將第二個 (x,y) 對追加到第一個:以下示例將在輸出中將 y1 和 y2 繪製在同一個 x 軸上。

x1 = [1,2,3,4]
y1 = [1,2,3,4]
y2 = [4,3,2,1]
plot(x1,y1,x1,y2)

極座標圖

[編輯 | 編輯原始碼]

使用 θ 和 r(θ) 繪製函式

t = 0:.01:2*pi;
polar(t,sin(2*t).^2)

三維圖形

[編輯 | 編輯原始碼]

"plot3" 命令非常有用,可以輕鬆地檢視三維影像。它遵循與 "plot" 命令相同的語法。如果你搜索 MATLAB 幫助(不要在命令提示符下。轉到主欄頂部的“幫助”選項卡,然後在搜尋框中鍵入 plot3),你會找到所有你需要說明。

示例

l=[-98.0556  ; 1187.074];       
f=[ -33.5448 ; -240.402];       
d=[ 1298     ; 1305.5]           
plot3(l,f,d); grid on;

此示例在三維空間中繪製一條線。我在 M 檔案中建立了此程式碼。如果你也這樣做,更改值並點選選單欄中的“執行”按鈕檢視效果。

使用向量 x 和 y 以及矩陣 z 建立三維圖。如果 x 的長度為 n 個元素,而 y 的長度為 m 個元素,則 z 必須為 m 行 n 列的矩陣。

示例

x=[0:pi/90:2*pi]';
y=x';
z=sin(x*y);
mesh(x,y,z);

等高線

[編輯 | 編輯原始碼]

使用向量 x 和 y 以及矩陣 z 建立三維投影的二維圖。如果 x 的長度為 n 個元素,而 y 的長度為 m 個元素,則 z 必須為 m 行 n 列的矩陣。

示例

x=[0:pi/90:2*pi]';
y=x';
z=sin(x*y);
contour(x,y,z);

填充等高線

[編輯 | 編輯原始碼]

與等高線相同,但填充等高線之間的顏色。

基本上與網格相同。

華夏公益教科書