--- title: 數學軟體實作 - Matlab-04-作圖 tags: 2020 Fall - 數學軟體實作 GA: G-77TT93X4N1 --- # `Matlab` 基礎 - Lecture 04 ## 作圖 - 2D: $y=f(x)$ ```matlab= %% 二維平面做圖, y=sin(x), -1<=x<=1. N = 100; % 作圖要取的點數 x = linspace(-1, 1, N); % 在 [-1, 1] 區間均勻取N個點 f = sin(x); % 計算函數 plot(x, f) % 作圖 plot(x, sin(x), x, cos(x)) % 兩個函數一起畫 %% 多個圖形重合, 另一種做法 plot(x, sin(x)) % 先畫第一張圖 hold on % 目前的圖保持住不要擦掉 plot(x, cos(x)) % 畫第二張圖 plot(x, sin(cos(x))) % 畫第三張圖 hold off % 可以擦掉了 plot(x, cos(sin(x))) ``` #### 基本原理 `x` 及 `y` 分別為向量, $$ x = [x_0, x_1, \cdots, x_n], \quad y = [y_0, y_1, \cdots, y_n]. $$ 而 `plot(x,y)` 指令所做的事就是將 $(x_0,y_0)$ 一直到 $(x_n, y_n)$ 這些點以直線段連起來. ## Exercise 4 若要畫三維中的曲線其指令是`plot3`, 試畫出以下參數化曲線 $$ x(t) = \cos(t), \quad y(t) = \sin(t), \quad z(t) = t, \quad 0\le t\le 8\pi $$ --- ### 曲線控制 ```matlab= %% Example from Matlab-plot x = -pi:pi/10:pi; % x 點座標 y = tan(sin(x)) - sin(tan(x)); % y 點座標 plot(x,y,'--rs',... % 虛線, 紅色, 方塊 'LineWidth',2,... % 線條寬度: 2 'MarkerEdgeColor','k',... % 方塊邊緣顏色: 黑 'MarkerFaceColor','g',... % 方塊顏色: 綠 'MarkerSize',10) % 方塊大小: 10 ``` | 指令 | 顏色 | 指令 | 圖示 | 指令 | 圖樣 | |---|---------|----|-------|----|-------| | b | blue | . | point | - | solid | | g | green | o | circle | : | dotted | | r | red | x | x-mark | -. | dashdot | | c | cyan | + | plus | -- | dashed | | m | magenta | * | star | (none) | no line | | y | yellow | s | square | | k | black | d | diamond | | w | white | v | triangle (down) | | | | ^ | triangle (up) | | | | < | triangle (left) | | | | > | triangle (right) | | | | p | pentagram | | | | h | hexagram | ### 圖軸控制 使用 `axis` 指令可以設定目前圖框 `x` 及 `y` 軸的範圍: `axis([XMIN XMAX YMIN YMAX])` 另外還有以下這些預設指令可以用: | 指令 | | | -------- | -------- | | axis equal | 兩軸比例一樣 | | axis image | 兩軸比例一樣, 不過畫框貼齊圖形 | | axis square | 圖框長寬比例為 1:1 | | axis normal | 回復預設長寬比例 | | axis off | 不顯示刻度畫框 | | axis on | 回復顯示刻度畫框 | ```matlab= %% Example x = linspace(-1,1); % [-1, 1] 之間取點, 不指定點數預設是 100 點 y = sqrt(1-x.^2); % y 點座標 plot(x,y) % 畫出上半圓 hold on % 圖形不擦掉 plot(x, -y) % 補畫下半圓 axis equal % 設定 x-y 軸比例一樣 ``` ### 子圖 - subplot 可以在一張圖裡併入幾張子圖, 指令為 `subplot(m,n,p)`. 意義是將一張圖分成 mxn 的幾張圖, 其中第 p 張. ```matlab= %% Example 1 x = linspace(-1,1); % [-1, 1] 之間取點 subplot(2, 1, 1); % 將圖表分成 2x1 兩塊, 第一塊 plot(x, sin(x)) % 畫出 sin(x) subplot(2, 1, 2); % 2x1 兩塊的第二塊 plot(x, cos(x)) % 畫出 cos(x) ``` ```matlab= %% Example 2 x = linspace(-1,1); % [-1, 1] 之間取點 subplot(2, 2, 1); % 將圖表分成 2x2 四塊, 第一塊 plot(x, sin(x)) % 畫出 sin(x) subplot(2, 2, 2); % 2x2 四塊的第二塊 plot(x, cos(x)) % 畫出 cos(x) subplot(2, 1, 2); % 割成 2x1 兩塊的第二塊 plot(x, sin(2*x)) % 畫出 sin(2x) ``` ## Exercise 5 寫一函數, 畫出以下 polar curve $$ r(\theta) = 1+c\sin(n\theta), \quad 0\le \theta\le 2\pi. $$ Hint: $$ x(\theta) = r(\theta)\cos(\theta), \quad y(\theta) = r(\theta)\sin(\theta). $$ 此函數 `input` 為正整數 `n` 以及實數向量 `c`. 向量`c`的每一個component都可對應至一個polar curve, 因此, for example, 若向量`c`為1x3向量, 就要畫出三條曲線. 舉例來說, 輸入 $n=1$, $c=[1, 2]$, 則要畫出 $$ r(\theta) = 1+\sin(\theta), \quad 0\le \theta\le 2\pi, $$ 以及 $$ r(\theta) = 1+2\sin(\theta), \quad 0\le \theta\le 2\pi, $$ 兩條曲線.