chap. 2 變數、陣列 矩陣運算與 相關函數

126
MATLAB 程程程程程程程程程 Chap. 2 程程 程程 程程程程程 程程程程 程程 程程程程程

Upload: jerry

Post on 23-Jan-2016

167 views

Category:

Documents


0 download

DESCRIPTION

Chap. 2 變數、陣列 矩陣運算與 相關函數. 方煒 台大生機系. 工作空間與變數的儲存及載入. MATLAB 在進行各種運算時,會將變數儲存在記憶體內,這些儲存變數的記憶體空間稱為基本工作空間( Base Workspace )或簡稱工作空間( Workspace) 若要檢視現存於工作空間( Workspace )的變數,可鍵入 who 若要知道這些變數更詳細的資料,可使用 whos 指令. The Workspace Browser. The Array Editor. 檢視工作空間變數的其他方式. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Chap. 2 變數、陣列矩陣運算與 相關函數

方煒 台大生機系

Page 2: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

工作空間與變數的儲存及載入 MATLAB 在進行各種運算時,會將變數儲存在記憶體內,這些儲存變數的記憶體空間稱為基本工作空間( Base Workspace )或簡稱工作空間( Workspace) 若要檢視現存於工作空間( Workspace )的變數,可鍵入 who

若要知道這些變數更詳細的資料,可使用 whos 指令

Page 3: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

The Workspace Browser

Page 4: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

The Array Editor

Page 5: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

檢視工作空間變數的其他方式 使用 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 的所有變數

Page 6: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

變數命名規則與使用 第一個字母必需是英文字母。 字母間不可留空格。 最多只能有 31 個字母。  使用變數時,不需預先經過變數宣告( Variable Declaration )

數值變數均以預設的 double 資料型式儲存。

Page 7: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

數字變數的格式

Page 8: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

永久變數i 或 j 基本虛數單位eps 系統的浮點精確度inf 無限大nan 或 NaN 非數值 (not a number) 如 0/0

pi 圓周率realmax 系統所能表示的最大數值realmin 系統所能表示的最小數值nargin 函數的輸入引數個數nargout 函數的輸出引數個數

tic, toc / clock

計時器開與關 / 含 “年 -月 -日 -時 -分 -秒”的字串

其他 date, ans, cputime, etime

Page 9: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

整段程式碼的計時方法 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;

Page 10: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

整段程式碼的計時方法 2a clock:

clock 指令可傳回現在的時間所形成的向量,包含6 個元素,分別是年、月、日、時、分、秒

例如: 執行:

>> round(clock) % 傳回現在的時間,並以整數形式顯示 結果:

ans = 2007 2 19 23 26 39

代表現在時間是 2007 年 2 月 19 日 23 時 26 分 39 秒

Page 11: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

整段程式碼的計時方法 2b etime :

etime 指令可傳回兩個時間的差值,並以秒數表示 將 clock 和 etime 指令合併使用,就可以計算一段程式碼的執行時間

結果:elapsedTime =

0.2660

t0 = clock; % 記錄現在的時間a = inv(rand(500)); % 執行反矩陣運算elapsedTime = etime(clock, t0) % 計算所耗費的總時間

Page 12: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

整段程式碼的計時方法 3 cputime :

cputime 可傳回 MATLAB 從啟動後所占用的 CPU 時間

範例 1-3 : cputime01.m

結果:cpuTime =

0.3500

t0 = cputime; % 記錄現在的時間a = inv(rand(500)); % 執行反矩陣運算cpuTime = cputime-t0 % 計算 CPU 所耗費的時間

Page 13: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

etime vs. cputime cputime :

cputime 指令回傳的時間並不包含讀檔、關檔等I/O 運算,所以其值會小於整段程式碼的實際執行時間

下面範例測試 etime 和 cputime 的差異mat = magic(50);t0 = clock;for i = 1:10; mesh(mat); endelapsedTime = etime(clock, t0) % 顯示實際經過時間t0 = cputime;for i = 1:10; mesh(mat); endcpuTime = cputime-t0 % 顯示 CPU 佔用時間

結果 :elapsedTime = 0.1810cpuTime = 0.1700

Page 14: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

DON’T >>circ1=2*pi*10; >>pi=3; >>circ2=2*pi*10; >>circ1 >>circ2

千萬不要用系統預設的永久變數為你的變數

Page 15: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

一維與二維陣列

Page 16: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Page 17: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Multidimensional Arrays

cat(n,A,B,C, ...)Creates a new array by

concatenating the arrays A,B,C, and so on along the dimension n.

Consist of two-dimensional matrices “layered” to produce a third dimension. Each “layer” is called a page.

Page 18: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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 = 2 4 10 16 3 7 8 4 9 3 12 15

矩陣與向量

Page 19: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

向量與矩陣MATLAB 中的變數還可用來儲存向量( Vectors )及矩陣( Matrix )

>> s1 = [1 3 5 2]; >> s2 = [1,3,5,2];

注意 [] 的使用各數字間的空白間隔以逗號分開亦可

Page 20: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

separate the elements by semicolons.

>>p = [3,7,9]p = 3 7 9

create a column vector by using the transpose notation (‘). 轉置矩陣

To create a row vector

>>p = [3,7,9]'p = 3 7 9

Page 21: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

You can also create a column vector by separating the elements by semicolons. For example,

>>g = [3;7;9]g = 3 7 9

比較轉置矩陣與 ROT90 函數的差別

Create a column vector

>>p = [3,7,9]'p = 3 7 9

Page 22: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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 ].

Page 23: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

generates a large vector

Page 24: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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

Page 25: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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 linspace command

Page 26: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

The logspace command

Page 27: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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 =

矩陣的建立

Page 28: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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

由向量建立矩陣

Page 29: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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 + x2

2 + … + 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.

向量的長度、大小與絕對值

Page 30: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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)).

範例

Page 31: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Vector addition by geometry.

(a) The parallelogram law.

(b) Addition of vectors in three dimensions.

Page 32: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Array Addition and Subtraction

6 –210 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+Bans = 15 6 -2 17

Page 33: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 火車以速度 60 miles/hr 向東,汽車以速度 45 miles/hr

向東北前進,兩者方向的夾角為 55 度。火車對汽車的相對速度為何?火車對汽車的相對速率為何?

VT= 60 i + 0 j Vc= 45 (cos(55o*pi/180) i + sin(55o*pi/180) j)

Page 34: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 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))

Page 35: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Geometric interpretation of scalar multiplication of a vector.

If r = [x, y, z],

then v = 2r

=2[x, y, z]

= [2x, 2y, 2z].

Page 36: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

32 95 –7

= 6 2715 –21

This multiplication is performed in MATLAB as follows:

>>A = [2, 9; 5,-7];>>3*Aans = 6 27 15 -21

scalar multiplication of a vector

Page 37: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

矩陣的各種處理 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

Page 38: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

• 單一變數可以代表一個陣列 / 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 次 .

矩陣的各種處理

Page 39: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

>>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

Array Index

Page 40: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

1. array multiplication (element-by-element multiplication),

2. matrix multiplication.

兩種乘法的定義

Page 41: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

[1 2][3

4]

Page 42: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

兩純量之間的運算

Page 43: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

兩陣列與矩陣之間的運算

Page 44: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Symbol

+

-

+

-

.*

./

.\

.^

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]

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

Element-by-element operations

Page 45: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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]

Element-by-element multiplication

Page 46: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

If x and y are column vectors, the result of x.*y is a column vector. For example z = (x’).*(y’) gives

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.

2(–7)4(3)

–5(–8)

–141240

=z =

Element-by-element multiplication

Page 47: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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

then C = A.*B gives this result:

A = 11 5 –9 4

B = –7 8 6 2

C = 11(–7) 5(8) –9(6) 4(2)

= –77 40–54 8

Element-by-element multiplication

Page 48: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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]

Array Division

A = 24 20– 9 4

B = –4 5 3 2

Also, if

then C = A./B gives

C = 24/(–4) 20/5 –9/3 4/2

= –6 4–3 2

Page 49: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

練習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]

Page 50: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

6x + 12y + 4z = 707x – 2y + 3z = 52x + 8y – 9z = 64

>>A = [6,12,4;7,-2,3;2,8,-9];>>B = [70;5;64];>>Solution = A\BSolution = 3 5 -2

The solution is x = 3, y = 5, and z = –2.

Solution of Linear Algebraic Equations

A X = B

X = A-1 B

Page 51: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 五條卡車貨運路線的行駛距離與行駛時間如下表:請問有最高行車速率的路線是哪一條?速率為多少?

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

Page 52: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 電阻 (R) 與電壓 (V) 數據如下表,請其出各自的電流 (I=V/R) 與消耗的功率 (P=V2/R).

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;

Page 53: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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].

Array Exponentiation

3.^p3.0.^p3..^p(3).^p3.^[2,4,5]

結果都一樣你看得出來嗎?

Page 54: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 依據牛頓運動定律,初速 v ,仰角 θ ,物體的最高高度為 h = v2*sin2(θ)/(2*g)

請建立一個表格,說明不同 v 與 θ 之下的 h 。 其中 v=10,12,14,16,18,20 m/s θ=50, 60, 70, 80 degree

Page 55: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例v= [10:2:20]; th=[50:10:80];thr=th*(pi/180);g=9.8;vel=[];%create the 6x4 array of speedsfor k=1:length(thr)

vel=[vel,v’];endtheta=[];%create the 6x4 array of anglesfor k=1:length(v)

Theta=[theta;thr];endh=(vel.^2.*(sin(theta)).^2)/(2*g);h=[v’,h];table=[0,th;H)

Page 56: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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,

6 –2 10 3 4 7

9 8–5 12

= (6)(9) + (– 2)(– 5) (6)(8) + (– 2)(12) (10)(9) + (3)(– 5) (10)(8) + (3)(12) (4)(9) + (7)(– 5) (4)(8) + (7)(12)

64 24 75 116 1 116

=

Matrix Multiplication

Page 57: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Use the operator * to perform matrix multiplication in MATLAB.

>>A = [6,-2;10,3;4,7];>>B = [9,8;-5,12];>>A*Bans = 64 24 75 116 1 116

Matrix Multiplication

Page 58: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 有三個產品均需要經過四道工序,所需時間與各工序的單位時間成本如下表,請問每一產品的生產成本各是多少?生產 10/5/7 個產品 1/2/3故需多少成本?

產出一單位產品需要的時間, hrs

工序 成本 $ /hr

產品 1 產品 2 產品 3

車削 10 6 5 4

研磨 12 2 3 1

銑 14 3 2 5

焊接 9 4 0 3

Page 59: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 A=[10,12,14,9];% hourly cost B=[6 2 3 4; 5 3 2 0; 4 1 5 3]; %time

required unitCst=A*B’ %answer is [162 114 149] C=[10 5 7];%No. of items totalCst=C*unitCst’%answer is 3233

Page 60: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例

U=[6,2,1;2,5,4;4,3,2;9,7,3];% 4 x 3 matrixP=[10,12,13,15;8,7,6,4;12,10,13,9;6,4,11,5];% 4 x 4 matrixC=U’*PQuarterly_cst=sum(C)%answer=[400 351 509 355]Category_cst=sum(C’)%answer=[760 539 316]

單位成本 $x103

產品 材料 人工 運輸1 6 2 1

2 2 5 4

3 4 3 2

4 9 7 3

各季產量產品 第 1

季第 2 季 第 3 季 第 4

季1 10 12 13 15

2 8 7 6 4

3 12 10 13 9

4 6 4 11 5

Page 61: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

that is, in general, ABBA. A simple example will demonstrate this fact:

AB = 6 –210 3

9 8–12 14

= 78 2054 122

BA = 9 8–12 14

6 –210 3

= 134 6 68 65

whereas

Reversing the order of matrix multiplication is a common and easily made mistake.

Matrix multiplication does not have the commutative property

Page 62: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

•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

Two exceptions to the noncommutative property

Page 63: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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 = 1 00 1

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.

The identity matrix

Page 64: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

建立大小為 m × n 的矩陣>> A = [1 2 3 4; 5 6 7 8; 9 10 11 12]; % 建立 3×4 的矩陣 A

>> A % 顯示矩陣 A 的內容A = 1 2 3 4 5 6 7 8 9 10 11 12

Page 65: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

m x n 矩陣的各種處理 % 將矩陣 A 第二列、第三行的元素值,改變為 5 >> A(2,3) = 5 A = 1 2 3 4 5 6 5 8 9 10 11 12

% 取出矩陣 A 的第二橫列、第一至第三直行,並儲存成矩陣 B

>> B = A(2,1:3)

B = 5 6 5

Page 66: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

m x n 矩陣的各種處理 (續 1) % 將矩陣 B 轉置後、再以行向量併入矩陣 A >> A = [A B'] A = 1 2 3 4 5 5 6 5 8 6 9 10 11 12 5

% 刪除矩陣 A 第二行(:代表所有橫列, [] 代表空矩陣) >> A(:, 2) = [] A = 1 3 4 5 5 5 8 6 9 11 12 5

Page 67: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

m x n 矩陣的各種處理 (續 2) >> A = [A; 4 3 2 1] % 在原矩陣 A 中,加入第四列 A = 1 3 4 5 5 5 8 6 9 11 12 5 4 3 2 1

>> A([1 4], :) = [] % 刪除第 1, 4 列(:代表所有直行, [] 是空矩陣)

A = 5 5 8 6 9 11 12 5

Page 68: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Colon (:) Command >>clear; clc; >>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];

請寫下由 A 到 F 的矩陣的內容

Page 69: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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. 

Page 70: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

You can use array indices to extract a smaller array from another array. For example, if you first create the array B

B =

C =16 3 7 8 4 9

2 4 10 1316 3 7 18 8 4 9 25 3 12 15 17

then type C = B(2:3,1:3), you can produce the following array:

Page 71: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

m x n 矩陣的各種處理 (續 3) array1=[1.1 -2.2 3.3 -4.4 5.5]; array1(3)=? [3.3] array1([1 4])=? [1.1 -4.4] array1(1:2:5)=? [1.1 3.3 5.5]

arr2=[1 2 3; -2 -3 -4; 3 4 5]; arr2(1,:)=? [1 2 3] arr2(:,1:2:3)=? [1 3; -2 -4; 3 5]

Page 72: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

m x n 矩陣的各種處理 5 >>arr3=[1 2 3 4 5 6 7 8]; arr3(5:end)=[5 6 7 8] arr3(end)=[8]

>>arr4=[1 2 3 4; 5 6 7 8; 9 10 11 12]; arr4(2:end;2:end)=? [6 7 8; 10 11 12] >>arr4(1:2, [1 4])=[20 21;22 23]; arr4 =? [20 2 3 21; 22 6 7 23; 9 10 11 12] >>arr4=[20 21; 22 23]; arr4=?

Page 73: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

m x n 矩陣的各種處理 6 >>arr4=[1 2 3 4; 5 6 7 8; 9 10 11 12]; >>arr4(1:2,1:2)=1 arr4= 1 1 3 4 1 1 7 8 9 10 11 12

Page 74: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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) 比較 length(arr?) 與 size(arr?) 的差別

Page 75: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

m x n 矩陣的初始格式化

Page 76: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Array Functionssize(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.

Page 77: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

Page 78: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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’)’

A = 6 2 –10 0 3 –5

練習

Page 79: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 五條卡車貨運路線的行駛距離與行駛時間如下表:請問有最高行車速率的路線是哪一條?速率為多少?

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)

Page 80: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

練習 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)

Page 81: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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 = 2 4 5

Vectorized functions

Page 82: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

Page 83: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例 動脈血壓模型 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)’);

Page 84: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

範例

Page 85: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

Order of Precedence

Page 86: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

>> 3*4^2 + 5ans = 53>>(3*4)^2 + 5ans = 149>>27^(1/3) + 32^(0.2)ans = 5>>27^(1/3) + 32^0.2ans = 5>>27^1/3 + 32^0.2ans = 11

Examples of Precedence

>> 8 + 3*5ans = 23>> 8 + (3*5)ans = 23>>(8 + 3)*5ans = 55>>4^2 12 8/4*2ans = 0>>4^2 12 8/(4*2)ans = 3

Page 87: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

常用數學函數 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])= [0.7071 1.0000 0.0000]

Page 88: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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)

cos1 x acos(x)

sin1 x asin(x)

tan1 x atan(x)

The MATLAB trigonometric functions use radian measure.

Page 89: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

數學函數 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)

Page 90: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Page 91: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用Common MATLAB functions

Page 92: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用其他常用函數

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) the integer remainder of x/y; see online help if x or y are negative

rot90(A) rotate a matrix A by 90

sign(x) the sign of x and returns 0 if x=0

Page 93: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Relational Meaning

operator

< Less than.<= Less than or equal to.> Greater than.>= Greater than or equal to.== Equal to.~= Not equal to.

Relational operators

Page 94: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

>> x = [6,3,9]; y = [14,2,9];>> z = (x < y)z =

1 0 0>>z = (x > y) z =

0 1 0>>z = (x ~= y)z =

1 1 0

Relational Operators 練習

>>z = (x == y)z =

0 0 1>>z = (x > 8)z =

0 0 1

Page 95: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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);

Page 96: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

Page 97: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

Page 98: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

To locate program errors

Page 99: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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.

Page 100: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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

Page 101: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

fprintf 之格式指令

Page 102: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

寫一個 myFun01.m 來計算下列函數

y = 0.5*exp(x/3)-x*x*sin(x) 其中 x 是函數的輸入, y 是函數的輸出。 你的函數必須能夠處理當 x 是純量或是向量的兩種情況。 此外,請利用下述兩列程式碼來畫出此函數的圖形:

function y = myFun01(x)y = 0.5*exp(x/3)-x.*x.*sin(x);

x=0:0.1:10; plot(x, myFun01(x));

Page 103: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

計算公式為 v = gt. 繪圖表示 v = f(t) for 0 ≤ t ≤ tf, 其中 tf 為使用者指定的最終時間

M file範例:自由落體運動

% 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)’)

Page 104: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

程式流程控制 MATLAB 提供重複迴圈( Loops )及條件判斷( Conditions )等程式流程控制( Flow Control )的指令 for 迴圈 For 變數 = 向量 運算式 ; end

Page 105: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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');

Page 106: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

fact01.m function output = fact01(n) % FACT01 Calculate factorial of a given positive integer (for-loop

version)

output = 1; for i = 1:n, output = output*i; end

Page 107: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

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);

Page 108: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

寫一個 程式 findN01.m ,求 n! > realmax 的最小 n 值

請問 n 值是多少?此時 (n-1)! 的值又是多少?

function findN01maxN = 1000; for n=1:maxN value = prod(1:n); if value>realmax break; end end fprintf('n = %d\n', n); fprintf('(n-1)! = %d\n', prod(1:n-1));

Page 109: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

函數 prod

Prod(1:2) Prod(1:3) Prod(1:4) Prod(1:1

0)

fact02(2)

fact02(3)

fact02(4)

fact02(10)

fact01(2)

fact01(3)

fact01(4)

fact01(10)

Page 110: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Page 111: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

寫一個 piFun01.m 來計算下列級數

f(n) = 4*(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...)其中 n 為函數的輸入, 代表上述級數的項數,

級數和 f(n) 則是函數的輸出。當 n夠大, f(n)趨近 pi

function out = piFun01(n) % approximate pitotal=0; for i=1:n item = (-1)^(i+1)/(2*i-1); total = total+item; end out = 4*total;

Page 112: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

End of Chapter 2

Page 113: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

HW # 1 靜力學問題 長度為 Lc的纜繩支撐長度為 Lb的樑柱,當樑柱末端懸掛重量為 W 時仍能保持水平。此纜繩的張力 T 為 Lb*Lc*W/(D*sqrt(Lb

2-D2)) 。

1. 對於 W=400 N, Lb=3 m, Lc=5 m 時,使用逐元運算以及 min 函數計算張力 T 為最小時的D ,並求出最小張力值。

2. 繪出 T對 D 的圖形,檢查解的靈敏度。當張力比其最小值增加 10 % 時, D 與最佳化的值的差異有多少?

Page 114: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

流程控制 while 迴圈( While-loop ) while 條件式 運算式 ; end

if – else – end if 條件式 運算式 ; else 運算式 ; end

Page 115: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

寫一個 遞迴函數 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 numberif n==1

out=0;return;

elseif n==2out=1;return;

elseout=fibo(n-1)+fibo(n-2);

end

Page 116: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

寫一個非遞迴函數 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);

Page 117: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

請寫一個函數 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];

Page 118: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

請寫一個函數 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);

Page 119: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

請寫一個函數 sort01.m ,當輸入為 a 時,可傳回 index2 ,滿足 a 等於 b(index2) 。以 a = [92, 95, 58, 75, 69, 82] 為例,傳回的 index2 應該是 [5, 6, 1, 3, 2, 4] ,顯示由小至大排列的排名。

Page 120: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Cell array functions

Function DescriptionC = 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 toX = A, Y = B, . . .

[X,Y, ...] = deal(A) Matches up the input and output lists. Equivalent toX = A, Y = A, . . .

iscell(C) Returns a 1 if C is a cell array; otherwise, returns a 0.

Page 121: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Arrangement of data in the structure array student

Page 122: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Structure functions

Function Descriptionnames = 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.

Page 123: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Structure functions

Function DescriptionS = 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’, . . . .

Page 124: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

• The number c1 = 1 – 2i is entered as follows: c1 = 1 2i.

• 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.5iand x = 7/(2i) = –3.5i.

MATLAB 也支援複數運算

Page 125: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

MATLAB 也支援複數運算 >> z=5+4j %複數 z=5+4 ,通常以 i 或 j 代表單位

虛數 z= 5.0000 + 4.0000 i

>> 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 的共軛複數 y= 5.0000 - 4.0000 i

1

1

Page 126: Chap. 2  變數、陣列 矩陣運算與 相關函數

MATLAB 程式設計與工程應用

Euler Identity 尤拉恆等式

>> y = exp(j*pi/6) %

y= 0.8660 + 0.5000 i

sincos je j

)6/cos(pi )6/sin( pi