Download presentation
Presentation is loading. Please wait.
1
Chap. 2 變數、陣列 矩陣運算與 相關函數 方煒 台大生機系
2
工作空間與變數的儲存及載入 MATLAB 在進行各種運算時,會將變數儲存在記憶體內,這些儲存變數的記憶體空間稱為基本工作空間(Base Workspace)或簡稱工作空間(Workspace) 若要檢視現存於工作空間(Workspace)的變數,可鍵入 who 若要知道這些變數更詳細的資料,可使用 whos 指令
3
The Workspace Browser
4
The Array Editor
5
檢視工作空間變數的其他方式 使用 clear 指令來清除或刪除工作空間內的某一特定或所有變數,以避免記憶體的閒置與浪費
clear A指令清除變數A clear all指令清除所有變數 不加任何選項(options)時,save 指令會將工作空間內的變數以二進制(Binary)的方式儲存至副檔名為 mat 的檔案,load 指令可讀取儲存的變數 save:將工作空間的所有變數以8位元大小儲存到名為 matlab.mat 的 二進制檔案。-double 可改用16位元大小儲存,-ascii可改用文字檔案格式儲存。 save filename:將工作空間所有變數儲存到名為 filename.mat的二進制檔案。 save filename x y z:將變數 x、y、z 儲存到名為 filename.mat 的二進制檔案。 load filename: 讀取儲存到名為 filename.mat的所有變數
6
變數命名規則與使用 第一個字母必需是英文字母。 字母間不可留空格。 最多只能有 31 個字母。
最多只能有 31 個字母。 使用變數時,不需預先經過變數宣告(Variable Declaration) 數值變數均以預設的 double 資料型式儲存。
7
數字變數的格式
8
永久變數 i 或 j 基本虛數單位 eps 系統的浮點精確度 inf 無限大 nan 或 NaN
非數值 (not a number) 如 0/0 pi 圓周率 realmax 系統所能表示的最大數值 realmin 系統所能表示的最小數值 nargin 函數的輸入引數個數 nargout 函數的輸出引數個數 tic, toc / clock 計時器開與關/ 含 “年-月-日-時-分-秒”的字串 其他 date, ans, cputime, etime
9
整段程式碼的計時方法1 碼表計時: tic 和 toc 指令,是最簡單的程式計時方法,只要將整段程式碼置於這兩個指令之中,MATLAB 就會自動計算程式執行所花費的時間 結果: Elapsed time is seconds 練習 tic % 開始計時 inv(rand(500)); % inv 指令是用來計算反矩陣 toc % 結束計時 tic; for i=1:1:10000; disp i; end; tac;
10
整段程式碼的計時方法2a clock: clock 指令可傳回現在的時間所形成的向量,包含 6 個元素,分別是年、月、日、時、分、秒 例如:
執行: >> round(clock) % 傳回現在的時間,並以整數形式顯示 結果: ans = 代表現在時間是 2007 年 2 月 19 日 23 時 26 分 39 秒
11
整段程式碼的計時方法2b etime: etime 指令可傳回兩個時間的差值,並以秒數表示
將 clock 和 etime 指令合併使用,就可以計算一段程式碼的執行時間 結果: elapsedTime = t0 = clock; % 記錄現在的時間 a = inv(rand(500)); % 執行反矩陣運算 elapsedTime = etime(clock, t0) % 計算所耗費的總時間
12
整段程式碼的計時方法3 cputime: cputime可傳回 MATLAB 從啟動後所占用的 CPU 時間
t0 = cputime; % 記錄現在的時間 a = inv(rand(500)); % 執行反矩陣運算 cpuTime = cputime-t0 % 計算 CPU 所耗費的時間
13
etime vs. cputime cputime:
cputime 指令回傳的時間並不包含讀檔、關檔等 I/O 運算,所以其值會小於整段程式碼的實際執行時間 下面範例測試 etime 和 cputime 的差異 mat = magic(50); t0 = clock; for i = 1:10; mesh(mat); end elapsedTime = etime(clock, t0) % 顯示實際經過時間 t0 = cputime; cpuTime = cputime-t0 % 顯示 CPU 佔用時間 結果 : elapsedTime = cpuTime =
14
DON’T 千萬不要用系統預設的永久變數為你的變數 >>circ1=2*pi*10; >>pi=3;
15
一維與二維陣列
17
Multidimensional Arrays
Consist of two-dimensional matrices “layered” to produce a third dimension. Each “layer” is called a page. Creates a new array by concatenating the arrays A,B,C, and so on along the dimension n. cat(n,A,B,C, ...)
18
矩陣與向量 A matrix has multiple rows and columns. For example, the matrix has four rows and three columns. Vectors are special cases of matrices having one row or one column. M =
19
向量與矩陣 MATLAB 中的變數還可用來儲存向量(Vectors)及矩陣(Matrix) >> s1 = [1 3 5 2];
注意 [] 的使用 各數字間的空白間隔 以逗號分開亦可
20
To create a row vector separate the elements by semicolons.
create a column vector by using the transpose notation (‘). 轉置矩陣 >>p = [3,7,9]' p = 3 7 9
21
Create a column vector You can also create a column vector by separating the elements by semicolons. For example, >>g = [3;7;9] g = 3 7 9 >>p = [3,7,9]' p = 3 7 9 比較轉置矩陣與 ROT90 函數的差別
22
Create vectors by ''appending'' one vector to another.
w = [9,-6,3]; >>u = [r,w] u = [ 2, 4, 20, 9, -6, 3]. >>u = [r ; w] [ ].
23
generates a large vector
The colon operator (:) easily generates a large vector of regularly spaced elements. Typing >>x = [m:q:n] creates a vector x of values with a spacing q. The first value is m. The last value is n if m - n is an integer multiple of q. If not, the last value is less than n.
24
For example, typing x = [0:2:8] creates the vector x = [0,2,4,6,8], whereas typing x = [0:2:7] creates the vector x = [0,2,4,6]. To create a row vector z consisting of the values from 5 to 8 in steps of 0.1, type z = [5:0.1:8]. >>x = [m: q: n] If the increment q is omitted, it is presumed to be 1. Thus typing y = [-3:2] produces the vector y = [-3,-2,-1,0,1,2]. 2-7
25
The linspace command also creates a linearly spaced row vector, but instead you specify the number of values rather than the increment. The syntax is linspace(x1,x2,n), where x1 and x2 are the lower and upper limits and n is the number of points. For example, linspace(5,8,31) is equivalent to [5:0.1:8]. If n is omitted, the spacing is 1.
26
The logspace command creates an array of logarithmically spaced elements. Its syntax is logspace(a,b,n), where n is the number of points between 10a and 10b. For example, x = logspace(-1,1,4) produces the vector x = [0.1000, , , ]. If n is omitted, the number of points defaults to 50.
27
矩陣的建立 If the matrix is small you can type it row by row, separating the elements in a given row with spaces or commas and separating the rows with semicolons. For example, typing >>A = [2,4,10;16,3,7]; creates the following matrix: Remember, spaces or commas separate elements in different columns, whereas semicolons separate elements in different rows. A =
28
由向量建立矩陣 a = [1,3,5] and b = [7,9,11] (row vectors). >>c = [a b];
>>D = [a;b] D =
29
向量的長度、大小與絕對值 Keep in mind the precise meaning of these terms when using MATLAB. The length command gives the number of elements in the vector. The magnitude of a vector x having elements x1, x2, …, xn is a scalar, given by Ö(x x22 + … + xn2), and is the same as the vector's geometric length. The absolute value of a vector x is a vector whose elements are the absolute values of the elements of x.
30
範例 x = [2,-4,5], its length is 3; (computed from length(x))
its magnitude is [22 + (–4)2 + 52] = ; (computed from sqrt(x’*x)) its absolute value is [2,4,5] (computed from abs(x)).
31
Vector addition by geometry.
(a) The parallelogram law. (b) Addition of vectors in three dimensions.
32
Array Addition and Subtraction
6 –2 – – + = Array subtraction is performed in a similar way. The addition shown performed in MATLAB as follows: >>A = [6,-2;10,3]; >>B = [9,8;-12,14] >>A+B ans = 15 6
33
範例 火車以速度 60 miles/hr 向東,汽車以速度 45 miles/hr 向東北前進,兩者方向的夾角為 55 度。火車對汽車的相對速度為何?火車對汽車的相對速率為何? VT= 60 i + 0 j Vc= 45 (cos(55o*pi/180) i + sin(55o*pi/180) j)
34
範例 VT= [60, 0]; Vc= 45 * [cos(55o*pi/180), sin(55o*pi/180)];
VR= VT – Vc S1R=sqrt(VR’*VR) S2R=sqrt(VR(1)^2+VR(2)^2) S3R=sqrt(sum(VR.*VR))
35
Geometric interpretation of scalar multiplication of a vector.
If r = [x, y, z], then v = 2r =2[x, y, z] = [2x, 2y, 2z].
36
scalar multiplication of a vector
5 –7 –21 = 3 This multiplication is performed in MATLAB as follows: >>A = [2, 9; 5,-7]; >>3*A ans = 6 27
37
矩陣的各種處理 MATLAB 亦可取出向量中的一個元素或一部份來做運算,例如:t = [3 7 11 5] t = 3 7 2 5
>> t(6) = 10 % 在向量 t 加入第六個元素,其值為 10 >> t(4) = [] % 將向量 t 的第四個元素刪除,[] 代表空集合
38
矩陣的各種處理 • 單一變數可以代表一個陣列 / array (矩陣)
當數字 0, 0.1, 0.2, …, 10 用變數 u 表示時,可以寫成 u = [0:0.1:10].這一個變數代表了 101 個數字 • 計算 w = 5 sin u for u = 0, 0.1, 0.2, …, 10, 程式寫法如下; >>u = [0:0.1:10]; >>w = 5*sin(u); • 這一行指令, w = 5*sin(u), 將該公式計算了 101 次.
39
Array Index >>u = [0:0.1:10]; w = 5*sin(u); >>u(7) ans =
0.6000 >>w(7) 2.8232 •使用 length 函數來瞭解陣列的長度. >>m = length(w) m = 101
40
兩種乘法的定義 1. array multiplication (element-by-element multiplication),
2. matrix multiplication.
41
[1 2] [3 4]
42
兩純量之間的運算
43
兩陣列與矩陣之間的運算
44
Element-by-element operations
Symbol + - .* ./ .\ .^ Operation Scalar-array addition Scalar-array subtraction Array addition Array subtraction Array multiplication Array right division Array left division Array exponentiation Form A + b A – b A + B A – B A.*B A./B A.\B A.^B Examples [6,3]+2=[8,5] [8,3]-5=[3,-2] [6,5]+[4,8]=[10,13] [6,5]-[4,8]=[2,-3] [3,5].*[4,8]=[12,40] [2,5]./[4,8]=[2/4,5/8] [2,5].\[4,8]=[2\4,5\8] [3,5].^2=[3^2,5^2] 2.^[3,5]=[2^3,2^5] [3,5].^[2,4]=[3^2,5^4]
45
Element-by-element multiplication
Array or Element-by-element multiplication is defined only for arrays having the same size. The definition of the product x.*y, where x and y each have n elements, is x.*y = [x(1)y(1), x(2)y(2), ... , x(n)y(n)] if x and y are row vectors. For example, if x = [2, 4, – 5], y = [– 7, 3, – 8] then z = x.*y gives z = [2(– 7), 4 (3), –5(–8)] = [–14, 12, 40]
46
Element-by-element multiplication
If x and y are column vectors, the result of x.*y is a column vector. For example z = (x’).*(y’) gives 2(–7) 4(3) –5(–8) –14 12 40 z = = Note that x’ is a column vector with size 3 × 1 and thus does not have the same size as y, whose size is 1 × 3. Thus for the vectors x and y the operations x’.*y and y.*x’ are not defined in MATLAB and will generate an error message.
47
Element-by-element multiplication
The array multiplication operation A.*B results in a matrix C that has the same size as A and B and has the elements ci j = ai j bi j . For example, if –9 4 –7 8 6 2 A = B = then C = A.*B gives this result: 11(–7) 5(8) –9(6) 4(2) – – C = =
48
Array Division The symbol for array right division is ./. For example, if x = [8, 12, 15] y = [–2, 6, 5] then z = x./y gives z = [8/(–2), 12/6, 15/5] = [–4, 2, 3] Also, if 24 20 – 9 4 –4 5 3 2 A = B = then C = A./B gives 24/(–4) 20/5 –9/ /2 –6 4 –3 2 C = =
49
練習 A=[1 0 ; 2 1] B=[-1 2; 0 1] C=[3; 2] D=5 (a) A+B=? (b) A.* B=?
(c) A*B=? (d) A*C=? (e) A+C=? (f) A+D=? (g) A.*D=? (h) A*D=? (a) [0 2;2 2] (b) [-1 0;0 1] (c) [-1 2;-2 5] (d) [3;8] (e) NA (f) [6 5;7 6] (g) [5 0;10 5] (h) [5 0;10 5]
50
Solution of Linear Algebraic Equations
6x + 12y + 4z = 70 7x – 2y + 3z = 5 2x + 8y – 9z = 64 >>A = [6,12,4;7,-2,3;2,8,-9]; >>B = [70;5;64]; >>Solution = A\B Solution = 3 5 -2 The solution is x = 3, y = 5, and z = –2. A X = B X = A-1 B
51
範例 五條卡車貨運路線的行駛距離與行駛時間如下表:請問有最高行車速率的路線是哪一條?速率為多少? 1 2 3 4 5 距離miles 560
440 490 530 370 時間hrs 10.3 8.2 9.1 10.1 7.5 >>d=[560,440,490,530,370]; >>t=[10.3,8.2,9.1,10.1,7.5]; >>spd=d./t
52
範例 電阻(R)與電壓(V)數據如下表,請其出各自的電流(I=V/R)與消耗的功率(P=V2/R). R=[…]; V=[..];
1 2 3 4 5 R (Ohms) 104 2x104 3.5x104 105 2x105 V (volts) 120 80 110 200 350 R=[…]; V=[..]; Current=V./R; Power=V.^2./R;
53
Array Exponentiation To perform exponentiation on an element-by-element basis, we must use the .^ symbol. For example, if x = [3, 5, 8], then typing x.^3 produces the array [33, 53, 83] = [27, 125, 512]. if p = [2, 4, 5], then typing 3.^p produces the array [32, 34, 35] = [9, 81, 243]. 3.^p 3.0.^p 3..^p (3).^p 3.^[2,4,5] 結果都一樣 你看得出來嗎?
54
範例 依據牛頓運動定律,初速v,仰角θ,物體的最高高度為 h = v2*sin2(θ)/(2*g)
其中 v=10,12,14,16,18,20 m/s θ=50, 60, 70, 80 degree
55
範例 v= [10:2:20]; th=[50:10:80];thr=th*(pi/180);g=9.8;
vel=[];%create the 6x4 array of speeds for k=1:length(thr) vel=[vel,v’]; end theta=[];%create the 6x4 array of angles for k=1:length(v) Theta=[theta;thr]; h=(vel.^2.*(sin(theta)).^2)/(2*g); h=[v’,h]; table=[0,th;H)
56
Matrix Multiplication
In the product of two matrices AB, the number of columns in A must equal the number of rows in B. The row-column multiplications form column vectors, and these column vectors form the matrix result. The product AB has the same number of rows as A and the same number of columns as B. For example, –2 (6)(9) + (– 2)(– 5) (6)(8) + (– 2)(12) (10)(9) + (3)(– 5) (10)(8) + (3)(12) (4)(9) + (7)(– 5) (4)(8) + (7)(12) 9 8 – = =
57
Matrix Multiplication
Use the operator * to perform matrix multiplication in MATLAB. >>A = [6,-2;10,3;4,7]; >>B = [9,8;-5,12]; >>A*B ans =
58
範例 有三個產品均需要經過四道工序,所需時間與各工序的單位時間成本如下表,請問每一產品的生產成本各是多少?生產10/5/7個產品1/2/3故需多少成本? 產出一單位產品需要的時間,hrs 工序 成本 $/hr 產品1 產品2 產品3 車削 10 6 5 4 研磨 12 2 3 1 銑 14 焊接 9
59
範例 A=[10,12,14,9];% hourly cost B=[ ; ; ]; %time required unitCst=A*B’ %answer is [ ] C=[10 5 7];%No. of items totalCst=C*unitCst’%answer is 3233
60
範例 單位成本 $x103 產品 材料 人工 運輸 1 6 2 5 4 3 9 7 各季產量 產品 第1季 第2季 第3季 第4季 1 10
12 13 15 2 8 7 6 4 3 9 11 5 U=[6,2,1;2,5,4;4,3,2;9,7,3];% 4 x 3 matrix P=[10,12,13,15;8,7,6,4;12,10,13,9;6,4,11,5];% 4 x 4 matrix C=U’*P Quarterly_cst=sum(C)%answer=[ ] Category_cst=sum(C’)%answer=[ ]
61
Matrix multiplication does not have the commutative property
that is, in general, AB ¹ BA. A simple example will demonstrate this fact: 6 –2 10 3 – AB = = whereas – 6 –2 BA = = Reversing the order of matrix multiplication is a common and easily made mistake.
62
Two exceptions to the noncommutative property
the null or zero matrix, denoted by 0 the identity, or unity, matrix, denoted by I. The null matrix contains all zeros and is not the same as the empty matrix [ ], which has no elements. These matrices have the following properties: 0A = A0 = 0 IA = AI = A
63
The identity matrix is a square matrix whose diagonal elements are all equal to one, with the remaining elements equal to zero. For example, the 2 × 2 identity matrix is I = The functions eye(n) and eye(size(A)) create an n × n identity matrix and an identity matrix the same size as the matrix A.
64
建立大小為 m × n的矩陣 >> A = [ ; ; ]; % 建立 3×4 的矩陣 A >> A % 顯示矩陣 A 的內容 A =
65
m x n矩陣的各種處理 % 將矩陣 A 第二列、第三行的元素值,改變為 5 >> A(2,3) = 5 A = 1 2 3 4
% 取出矩陣 A 的第二橫列、第一至第三直行,並儲存成矩陣 B >> B = A(2,1:3) B =
66
m x n矩陣的各種處理(續1) >> A(:, 2) = [] % 將矩陣 B 轉置後、再以行向量併入矩陣 A
>> A = [A B'] A = % 刪除矩陣 A 第二行(:代表所有橫列,[]代表空矩陣) >> A(:, 2) = []
67
m x n矩陣的各種處理(續2) >> A = [A; 4 3 2 1] % 在原矩陣 A 中,加入第四列 A =
>> A([1 4], :) = [] % 刪除第1, 4列(:代表所有直行,[]是空矩陣)
68
Colon (:) Command 請寫下 >>clear; clc; 由A到F的矩陣的內容 >>x=0:1:10;
>>A=magic(x(2)); >>B=A(:,2); >>C=A(2,:); >>D=A(2,1:2); >>E=[A B]; >>F=[A;C];
69
Array Addressing The colon operator selects individual elements, rows, columns, or ''subarrays'' of arrays. Here are some examples: v(:) represents all the row or column elements of the vector v. v(2:5) represents the second through fifth elements; that is v(2), v(3), v(4), v(5). A(:,3) denotes all the elements in the third column of the matrix A. A(:,2:5) denotes all the elements in the second through fifth columns of A. A(2:3,1:3) denotes all the elements in the second and third rows that are also in the first through third columns.
70
then type C = B(2:3,1:3), you can produce the following array:
You can use array indices to extract a smaller array from another array. For example, if you first create the array B B = then type C = B(2:3,1:3), you can produce the following array: C =
71
m x n矩陣的各種處理(續3) array1=[1.1 -2.2 3.3 -4.4 5.5]; array1(3)=? [3.3]
72
m x n矩陣的各種處理5 >>arr3=[1 2 3 4 5 6 7 8]; arr3(5:end)=[5 6 7 8]
arr4(2:end;2:end)=? [6 7 8; ] >>arr4(1:2, [1 4])=[20 21;22 23]; arr4 =? [ ; ; ] >>arr4=[20 21; 22 23]; arr4=?
73
m x n矩陣的各種處理6 >>arr4=[1 2 3 4; 5 6 7 8; 9 10 11 12];
74
m x n矩陣的各種處理7 >>arr5=zeros(4) >>arr6=ones(4)
>>arr7=eye(4) % 單元矩陣 比較 length(arr?) 與 size(arr?)的差別 >>arr5=zeros(3,4) >>arr6=ones(3,4) >>arr7=eye(3,4)
75
m x n矩陣的初始格式化
76
Array Functions size(A)
Returns a row vector [m n] containing the sizes of the m x n array A. sort(A) Sorts each column of the array A in ascending order and returns an array the same size as A. sum(A) Sums the elements in each column of the array A and returns a row vector containing the sums. max(A) Returns the algebraically largest element in A if A is a vector. Returns a row vector containing the largest elements in each column if A is a matrix. If any of the elements are complex, max(A) returns the elements that have the largest magnitudes. min(A) Like max but returns minimum values. Length(A) Computes either the number of elements of A if A is a vector or the largest value of m or n if A is an m × n matrix.
77
Advanced Array Functions
[b, k] = sort(A) Sorts each column of the array A in ascending order and returns a row vector b and their indices in the row vector k. [x, k] = max(A) Similar to max(A) but stores the maximum values in the row vector x and their indices in the row vector k. [x, k] = min(A) Like max but returns minimum values. [u,v,w] = find(A) Computes the arrays u and v, containing the row and column indices of the nonzero elements of the matrix A, and the array w, containing the values of the nonzero elements. The array w may be omitted.
78
練習 max(A) returns the vector [6,2];
– –5 A = max(A) returns the vector [6,2]; min(A) returns the vector [-10, -5]; size(A) returns [3, 2]; length(A) returns 3. sum(A) returns [-1 -3] 得到”行加總” 請問如何求列加總 ? sum(A’)’
79
範例 五條卡車貨運路線的行駛距離與行駛時間如下表:請問有最高行車速率的路線是哪一條?速率為多少? 1 2 3 4 5 距離miles 560
440 490 530 370 時間hrs 10.3 8.2 9.1 10.1 7.5 >>d=[560,440,490,530,370]; >>t=[10.3,8.2,9.1,10.1,7.5]; >>[h_spd, route]=max(d./t)
80
練習 sort 指令 a = [92, 95, 58, 75, 69, 82],執行 sort 指令:
[b, index] = sort(a) 會得到 b = [58, 69, 75, 82, 92, 95] 及 index = [3, 5, 4, 6, 1, 2] 其中 index 的每個元素代表 b 的每個元素在 a 的位置, 滿足 b 等於 a(index)
81
Vectorized functions The built-in MATLAB functions such as sqrt(x) and exp(x) automatically operate on array arguments to produce an array result the same size as the array argument x. Thus these functions are said to be vectorized functions. For example, in the following session the result y has the same size as the argument x. >>x = [4, 16, 25]; >>y = sqrt(x) y =
82
When multiplying or dividing vectorized functions, or when raising them to a power, you must use element-by-element operations if the arguments are arrays. For example, to compute z = (ey sin x) cos2x, you must type z = exp(y).*sin(x).*(cos(x)).^2. You will get an error message if the size of x is not the same as the size of y. The result z will have the same size as x and y.
83
範例 動脈血壓模型 y(t): 心臟動脈瓣膜壓差的常規化函數 (無單位) t: 時間,單位為秒
y(t) = e-8t sin(9.7 t + pi/2) >> t =[0:0.003:0.5]; >>y=exp(-8*t).*sin(9.7*t+pi/2); >>plot(t,y); >>xlabel(‘t (sec)’); >>ylabel(‘Normalized Pressure Difference y(t)’);
84
範例
85
Order of Precedence Precedence Operation
First Parentheses, evaluated starting with the innermost pair. Second Exponentiation, evaluated from left to right. Third Multiplication and division with equal precedence, evaluated from left to right. Fourth Addition and subtraction with equal precedence, evaluated from left to right.
86
Examples of Precedence
>> 3*4^2 + 5 ans = 53 >>(3*4)^2 + 5 149 >>27^(1/3) + 32^(0.2) 5 >>27^(1/3) + 32^0.2 >>27^1/3 + 32^0.2 11 >> 8 + 3*5 ans = 23 >> 8 + (3*5) >>(8 + 3)*5 55 >>4^212 8/4*2 >>4^212 8/(4*2) 3
87
常用數學函數 MATLAB 可以支援很多常用到的數學函數 >> y = abs(x) % 取 x 的絕對值
>> y = sin(x) % 取 x 的正弦值 >> y = cos(x) % 取 x 的餘弦值 >> y = tan(x) % 取 x 的正切值 >> y = exp(x) % 自然指數 exp(x) >> y = log(x) % 自然對數 ln(x) sin([pi/4,pi/2,pi])= [ ]
88
Function MATLAB syntax
ex exp(x) √x sqrt(x) ln x log(x) log10 x log10(x) cos x cos(x) sin x sin(x) tan x tan(x) cos-1 x acos(x) sin-1 x asin(x) tan-1 x atan(x) The MATLAB trigonometric functions use radian measure.
89
數學函數 cos(x) sin(x) tan(x) sec(x) csc(x) cot(x)
acos(x) asin(x) atan(x) atan2(y,x) exp(x) log(x) log10(x) log2(x) sqrt(x) cosh(x) sinh(x) tanh(x) sech(x) csch(x) coth(x) acosh(x) asinh(x) atanh(x) sign(x) airy(n,x) besselh(n,x) besseli(n,x) besselj(n,x) besselk(n,x) bessely(n,x) beta(x,y) betainc(x,y,z) betaln(x,y) ellipj(x,m) ellipke(x) erf(x) erfc(x) erfcx(x) erfinv(x) gamma(x) gammainc(x,a) gammaln (x) expint(x) legendre(n,x) factorial(x)
91
Common MATLAB functions
92
其他常用函數 clc clears the command window close all
closes all figure windows close 3 closes figure window 3 fliplr(A) flip a matrix A, left for right flipud(A) flip a matrix A, up for down mod(x,y) the integer remainder of x/y; see online help if x or y are negative rem(x,y) rot90(A) rotate a matrix A by 90 sign(x) the sign of x and returns 0 if x=0
93
Relational operators Relational Meaning operator < Less than.
<= Less than or equal to. > Greater than. >= Greater than or equal to. == Equal to. ~= Not equal to.
94
Relational Operators 練習
>> x = [6,3,9]; y = [14,2,9]; >> z = (x < y) z = 1 0 0 >>z = (x > y) 0 1 0 >>z = (x ~= y) 1 1 0 >>z = (x == y) z = 0 0 1 >>z = (x > 8)
95
m 檔案 若要一次執行大量的 MATLAB 指令,可將這些指令存放於一個副檔名為 m 的檔案,並在 指令提示號(>>)下鍵入此檔案主檔名即可。 >> pwd % 顯示目前的工作目錄 >> dir 顯示目前工作目錄的內容 >> cd 可改變工作目錄 >> type myTest.m % 顯示 myTest.m 的內容 >> myTest % 執行 myTest.m “Save and Run” shortcut key, F5. m file中程式太長可用… 連接a=sin(x)*exp(-y)*... log(z)+sqrt(b);
96
Keep in mind when using script files
1. The name of a script file must begin with a letter, and may include digits and the underscore character, up to 31 characters. 2. Do not give a script file the same name as a variable. 3. Do not give a script file the same name as a MATLAB command or function. You can check to see if a command, function or file name already exists by using the exist command.
97
Debugging Script Files
Program errors usually fall into one of the following categories. 1. Syntax errors such as omitting a parenthesis or comma, or spelling a command name incorrectly. MATLAB usually detects the more obvious errors and displays a message describing the error and its location. 2. Errors due to an incorrect mathematical procedure, called runtime errors. Their occurrence often depends on the particular input data. A common example is division by zero.
98
To locate program errors
try the following: 1. Test your program with a simple version of the problem which can be checked by hand. 2. Display any intermediate calculations by removing semicolons at the end of statements. 3. Use the debugging features of the Editor/Debugger.
99
Input/output commands
disp(A) Displays the contents, but not the name, of the array A. disp(’text’) Displays the text string enclosed within quotes. x = input(’text’) Displays the text in quotes, waits for user input from the keyboard, and stores the value in x. x = input(’text’,’s’) Displays the text in quotes, waits for user input from the keyboard, and stores the input as a string in x.
100
fprintf 指令 fprintf(’ N =%g \n’,500) fprintf(’ x =%1.12g \n’,pi)
fprintf(’ x =%1.10e \n’,pi) fprintf(’ x =%6.2f \n’,pi) fprintf(’ x =%12.8f y =%12.8f \n’,5,exp(5)) Note: \n is the command for a new line. For full information type >>help fprintf
101
fprintf 之格式指令
102
y = 0.5*exp(x/3)-x*x*sin(x)
寫一個 myFun01.m 來計算下列函數 y = 0.5*exp(x/3)-x*x*sin(x) 其中 x 是函數的輸入,y 是函數的輸出。 你的函數必須能夠處理當 x 是純量或是向量的兩種情況。 此外,請利用下述兩列程式碼來畫出此函數的圖形: x=0:0.1:10; plot(x, myFun01(x)); function y = myFun01(x) y = 0.5*exp(x/3)-x.*x.*sin(x);
103
M file範例:自由落體運動 計算公式為 v = gt. 繪圖表示 v = f(t) for 0 ≤ t ≤ tf, 其中 tf 為使用者指定的最終時間 % Program falling_speed.m: % Plots speed of a falling object. % Input Variable: tf = final time (in sec.) % Output Variables: % t = array of times at which speed is computed (in sec.) % v = array of speeds (m/s) % Parameter Value: g = 9.81; % Acceleration in SI units % % Input section: tf = input(’Enter final time in seconds:’); % Calculation section: dt = tf/500; % Create an array of 501 time values. t = [0:dt:tf]; % Compute speed values. v = g*t; % % Output section: Plot(t,v),xlabel(’t (s)’),ylabel(’v m/s)’)
104
程式流程控制 MATLAB 提供重複迴圈(Loops)及條件判斷(Conditions)等程式流程控制(Flow Control)的指令
for 迴圈 For 變數 = 向量 運算式; end
105
myTest.m % myTest: my first test M-file.
fprintf('Start of myTest.m!\n'); for i = 1:3 fprintf('i = %d ---> i^3 = %d\n', i, i^3); end fprintf('End of myTest.m!\n');
106
fact01.m function output = fact01(n) output = 1; for i = 1:n,
% FACT01 Calculate factorial of a given positive integer (for-loop version) output = 1; for i = 1:n, output = output*i; end
107
fact02.m function output = fact02(n)
% FACT2 Calculate factorial of a given positive integer (recursive version) if n == 1, % Terminating condition output = 1; return; end output = n*fact02(n-1);
108
寫一個 程式 findN01.m,求 n! > realmax的最小n 值
請問 n 值是多少?此時 (n-1)! 的值又是多少? function findN01 maxN = 1000; for n=1:maxN value = prod(1:n); if value>realmax break; end fprintf('n = %d\n', n); fprintf('(n-1)! = %d\n', prod(1:n-1));
109
函數 prod Prod(1:2) Prod(1:3) Prod(1:4) Prod(1:10) fact01(2) fact01(3)
111
寫一個 piFun01.m 來計算下列級數 f(n) = 4*(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/ ) 其中 n 為函數的輸入, 代表上述級數的項數, 級數和 f(n) 則是函數的輸出。當n夠大, f(n)趨近pi function out = piFun01(n) % approximate pi total=0; for i=1:n item = (-1)^(i+1)/(2*i-1); total = total+item; end out = 4*total;
112
End of Chapter 2
113
HW #1 靜力學問題 長度為Lc的纜繩支撐長度為Lb的樑柱,當樑柱末端懸掛重量為W時仍能保持水平。此纜繩的張力T為 Lb*Lc*W/(D*sqrt(Lb2-D2)) 。 對於W=400 N, Lb=3 m, Lc=5 m時,使用逐元運算以及min 函數計算張力T為最小時的D,並求出最小張力值。 繪出T對D的圖形,檢查解的靈敏度。當張力比其最小值增加10 % 時,D與最佳化的值的差異有多少?
114
流程控制 while 迴圈(While-loop) if – else – end while 條件式 運算式; end else
115
寫一個 遞迴函數 fibo.m 來計算 Fibonacci 數列
定義如下:fibo(n+2) = fibo(n+1)+fibo(n) 此數列的啟始條件:fibo(1) = 0, fibo(2) = 1. 使用 tic 和 toc 指令來測量 fibo(25) 的計算時間。 function out = fibo(n) % fibo: Fibonacci number if n==1 out=0; return; elseif n==2 out=1; else out=fibo(n-1)+fibo(n-2); end
116
寫一個非遞迴函數 fibo2.m 來計算 Fibonacci 數列
Fibonacci 數列的第 n 項可以直接表示成 fibo2(n)={[(1+a)/2]^(n-1)-[(1-a)/2]^(n-1)}/a 其中 a 是 5 的平方根。 請計算 fibo2(25) 的計算時間,並和 fibo(25) 比較。 function out = fibo2(n) % Fibonacci number using an analytic expression r1=(1+sqrt(5))/2; r2=(1-sqrt(5))/2; out=(r1^(n-1)-r2^(n-1))/sqrt(5);
117
請寫一個函數 minxy.m, 其功能是由一個二維矩陣中找出小元素
[minValue, minIndex] = minxy(matrix) 其中 matrix 是一個二維矩陣,minValue 則是其元素的最小值,而 minIndex 是長度為 2 的正整數向量,代表最小值的索引。換句話說,matrix(minIndex(1), minIndex(2)) 的值即是 minValue。 請測試 [minValue, minIndex] = minxy(magic(20)) 所傳回來的 minValue 和 minIndex 各是多少? function [minValue, minIndex] = minxy(matrix) %Minimum of a 2D matrix % Usage: [minValue, minIndex] = minxy(A) % minValue: the minimum of the matrix A % minIndex: the 2D index of minValue in A [columnMin, columnMinIndex] = min(matrix); [minValue, tmp] = min(columnMin); minIndex = [columnMinIndex(tmp) tmp];
118
請寫一個函數 ranking01.m, 輸入為成績向量 x,輸出則是此成績的排名
function out = ranking01(x) % ranking: Ascending ranking of element of x % x = [92, 95, 58, 75, 69, 82] 時,ranking01(x) 回傳的排名向量則是 % [2, 1, 6, 4, 5, 3],代表 92 分是排名第 2,82 分是排名第 3。 [sorted, position]=sort(-x); % 由大到小排列 n=length(x); rank=1:n; [junk, index]=sort(position); out=rank(index);
119
請寫一個函數 sort01.m,當輸入為 a 時,可傳回 index2,滿足 a 等於 b(index2)。以a = [92, 95, 58, 75, 69, 82] 為例,傳回的 index2 應該是 [5, 6, 1, 3, 2, 4],顯示由小至大排列的排名。
120
Cell array functions Function Description C = cell(n)
Creates an n × n cell array C of empty matrices. C = cell(n,m) Creates an n × m cell array C of empty matrices. celldisp(C) Displays the contents of cell array C. cellplot(C) Displays a graphical representation of the cell array C. C = num2cell(A) Converts a numeric array A into a cell array C. [X,Y, ...] = deal(A,B, ...) Matches up the input and output lists. Equivalent to X = A, Y = B, . . . [X,Y, ...] = deal(A) X = A, Y = A, . . . iscell(C) Returns a 1 if C is a cell array; otherwise, returns a 0.
121
Arrangement of data in the structure array student
122
Structure functions Function Description
names = fieldnames(S) Returns the field names associated with the structure array S as names, a cell array of strings. F = getfield(S,’field’) Returns the contents of the field ’field’ in the structure array S. Equivalent to F = S.field. isfield(S,’field’) Returns 1 if ’field’ is the name of a field in the structure array S, and 0 otherwise.
123
Structure functions Function Description
S = rmfield(S,’field’) Removes the field ’field’ from the structure array S. S = setfield(S,’field’,V) Sets the contents of the field ’field’ to the value V in the structure array S. S = struct(’f1’,’v1’,’f2’,’v2’,...) Creates a structure array with the fields ’f1’, ’f2’, having the values ’v1’, ’v2’,
124
MATLAB 也支援複數運算 • The number c1 = 1 – 2i is entered as follows: c1 = 12i. • An asterisk is not needed between i or j and a number, although it is required with a variable, such as c2 = 5 i*c1. • Be careful. The expressions y = 7/2*i and x = 7/2i give two different results: y = (7/2)i = 3.5i and x = 7/(2i) = –3.5i.
125
MATLAB 也支援複數運算 >> z=5+4j %複數z=5+4 ,通常以 i 或 j 代表單位虛數
>> z=5+4i %這也是複數z=5+4 >> y=angle(z) %複數z 的相角 y= 0.6747 >> y = real(z) %複數z 的實部 >> y =imag(z) %複數z 的虛部 >> y =conj(z) %複數z 的共軛複數 >> y = z’ %這也是複數z 的共軛複數 i
126
Euler Identity 尤拉恆等式 >> y = exp(j*pi/6) % y= i
Similar presentations