1.27k likes | 1.71k Views
Chap. 2 變數、陣列 矩陣運算與 相關函數. 方煒 台大生機系. 工作空間與變數的儲存及載入. MATLAB 在進行各種運算時,會將變數儲存在記憶體內,這些儲存變數的記憶體空間稱為基本工作空間( Base Workspace )或簡稱工作空間( Workspace) 若要檢視現存於工作空間( Workspace )的變數,可鍵入 who 若要知道這些變數更詳細的資料,可使用 whos 指令. The Workspace Browser. The Array Editor. 檢視工作空間變數的其他方式.
E N D
Chap. 2 變數、陣列矩陣運算與 相關函數 方煒 台大生機系
工作空間與變數的儲存及載入 • MATLAB 在進行各種運算時,會將變數儲存在記憶體內,這些儲存變數的記憶體空間稱為基本工作空間(Base Workspace)或簡稱工作空間(Workspace) • 若要檢視現存於工作空間(Workspace)的變數,可鍵入 who • 若要知道這些變數更詳細的資料,可使用 whos 指令
檢視工作空間變數的其他方式 • 使用 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的所有變數
變數命名規則與使用 • 第一個字母必需是英文字母。 • 字母間不可留空格。 • 最多只能有 31 個字母。 • 使用變數時,不需預先經過變數宣告(Variable Declaration) • 數值變數均以預設的 double 資料型式儲存。
整段程式碼的計時方法1 • 碼表計時: • tic 和 toc 指令,是最簡單的程式計時方法,只要將整段程式碼置於這兩個指令之中,MATLAB 就會自動計算程式執行所花費的時間 • 結果: Elapsed time is 0.886899 seconds • 練習 tic % 開始計時 inv(rand(500)); % inv 指令是用來計算反矩陣 toc % 結束計時 tic; for i=1:1:10000; disp i; end; tac;
整段程式碼的計時方法2a • clock: • clock 指令可傳回現在的時間所形成的向量,包含 6 個元素,分別是年、月、日、時、分、秒 • 例如: • 執行: >> round(clock) % 傳回現在的時間,並以整數形式顯示 • 結果:ans = 2007 2 19 23 26 39 • 代表現在時間是 2007 年 2 月 19 日 23 時 26 分 39 秒
整段程式碼的計時方法2b • etime: • etime 指令可傳回兩個時間的差值,並以秒數表示 • 將 clock 和 etime 指令合併使用,就可以計算一段程式碼的執行時間 • 結果:elapsedTime = 0.2660 t0 = clock; % 記錄現在的時間 a = inv(rand(500)); % 執行反矩陣運算 elapsedTime = etime(clock, t0) % 計算所耗費的總時間
整段程式碼的計時方法3 • cputime: • cputime可傳回 MATLAB 從啟動後所占用的 CPU 時間 • 範例1-3:cputime01.m • 結果:cpuTime = 0.3500 t0 = cputime; % 記錄現在的時間 a = inv(rand(500)); % 執行反矩陣運算 cpuTime = cputime-t0 % 計算 CPU 所耗費的時間
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; for i = 1:10; mesh(mat); end cpuTime = cputime-t0 % 顯示 CPU 佔用時間 • 結果 :elapsedTime = 0.1810cpuTime = 0.1700
DON’T • >>circ1=2*pi*10; • >>pi=3; • >>circ2=2*pi*10; • >>circ1 • >>circ2 • 千萬不要用系統預設的永久變數為你的變數
cat(n,A,B,C, ...) Creates a new array by concatenating the arrays A,B,C, and so on along the dimension n. Multidimensional Arrays Consist of two-dimensional matrices “layered” to produce a third dimension. Each “layer” is called a page.
矩陣與向量 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. 2 4 10 16 3 7 8 4 9 3 12 15 M =
向量與矩陣 • MATLAB 中的變數還可用來儲存向量(Vectors)及矩陣(Matrix) >> s1 = [1 3 5 2]; >> s2 = [1,3,5,2]; 注意 [] 的使用 各數字間的空白間隔 以逗號分開亦可
To create a row vector separate the elements by semicolons. >>p = [3,7,9] p = 3 7 9 create a column vector by using the transpose notation (‘). 轉置矩陣 >>p = [3,7,9]' p = 3 7 9
Create acolumn 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 函數的差別
Create vectors by ''appending'' one vector to another. • r = [2,4,20]; • w = [9,-6,3]; • >>u = [r,w] • u = • [ 2, 4, 20, 9, -6, 3]. • >>u = [r ; w] • u = • [ 2 4 20 • 9 -6 3 ].
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.
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
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.
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, 0.4642, 2.1544, 10.000]. If n is omitted, the number of points defaults to 50.
矩陣的建立 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: 2 4 10 16 3 7 Remember, spaces or commas separate elements in different columns, whereas semicolons separate elements in different rows. A =
由向量建立矩陣 a =[1,3,5] and b = [7,9,11] (row vectors). >>c = [a b]; c = 1 3 5 7 9 11 >>D = [a;b] D = 1 3 5 7 9 11
向量的長度、大小與絕對值 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 Ö(x12 + 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.
範例 x = [2,-4,5], its length is 3; (computed from length(x)) its magnitude is [22 + (–4)2 + 52] = 6.7082; (computed from sqrt(x’*x)) its absolute value is [2,4,5] (computed from abs(x)).
Vector addition by geometry. (a) The parallelogram law. (b) Addition of vectors in three dimensions.
Array Addition and Subtraction 6 –2 10 3 9 8 –12 14 15 6 –2 17 + = 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 -2 17
範例 • 火車以速度 60 miles/hr 向東,汽車以速度 45 miles/hr 向東北前進,兩者方向的夾角為 55 度。火車對汽車的相對速度為何?火車對汽車的相對速率為何? • VT= 60 i + 0 j • Vc= 45 (cos(55o*pi/180) i + sin(55o*pi/180) j)
範例 • 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))
Geometric interpretation of scalar multiplication of a vector. If r = [x, y, z], then v = 2r =2[x, y, z] = [2x, 2y, 2z].
scalar multiplication of a vector 2 9 5 –7 6 27 15 –21 = 3 This multiplication is performed in MATLAB as follows: >>A = [2, 9; 5,-7]; >>3*A ans = 6 27 15 -21
矩陣的各種處理 • MATLAB 亦可取出向量中的一個元素或一部份來做運算,例如:t = [3 7 11 5] >> t(3) = 2 % 將向量 t 的第三個元素更改為 2 t = 3 7 2 5 >> t(6) = 10 % 在向量 t 加入第六個元素,其值為 10 t = 3 7 2 5 0 10 >> t(4) = [] % 將向量 t 的第四個元素刪除,[] 代表空集合 t = 3 7 2 0 10
矩陣的各種處理 •單一變數可以代表一個陣列 / 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 次.
Array Index >>u = [0:0.1:10]; w = 5*sin(u); >>u(7) ans = 0.6000 >>w(7) ans = 2.8232 •使用 length 函數來瞭解陣列的長度. >>m = length(w) m = 101
兩種乘法的定義 1. array multiplication (element-by-element multiplication), 2. matrix multiplication.
[3 4] [1 2]
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]
Element-by-element multiplication Array or Element-by-element multiplication is defined only for arrays having the same size. The definition of the productx.*y, where x and y each havenelements, 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]
Element-by-element multiplication If x and y are column vectors, the result ofx.*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.
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 11 5 –9 4 –7 8 6 2 A = B = then C = A.*B gives this result: 11(–7) 5(8) –9(6) 4(2) –77 40 –54 8 C = =
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/3 4/2 –6 4 –3 2 C = =
練習 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]
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 isx = 3, y = 5,andz = –2. A X = B X = A-1 B