147
Introduction of MATLAB © PSE Laboratory Department of Chemical Engineering National Taiwan University Speaker: Shih-Wei Liu (劉士暐) E-mail [email protected] Date: 09/01/2011 MATLAB 2011 workshop

MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

Introduction of MATLABcopy

PSE Laboratory

Department of Chemical Engineering

National Taiwan University

Speaker Shih-Wei Liu (劉士暐)

E-mail f96524066ntueduw

Date 09012011

MATLAB 2011 workshop

147

Introduction

2

應用領域

高科技運算程式解決方案 Technical Computing

控制設計 Control Design

訊號處理及通訊 Signal Processing and

Communications

影像處理 Image Processing

測試及量測 Test Measurement

生物運算 Computational Biology

財務模型及分析 Financial Modeling and Analysis

教育專區 Education

147

Outline

3

1

2

3

Fundamentals of MATLAB

Plotting

Simulink

4 Implemetation

5 Summary

147

1計中網頁(httpsoftbankccntuedutwUser2html)

2使用方式第一次使用首先點選右下方lsquo安裝驅動軟體rsquo非第一次使用請直接跳至第13項

軟體取得

4

147

3請選擇lsquo從程式目前所在位置執行這個程式(R)lsquo後再按確定鍵

軟體取得

5

147

4請選擇lsquo是(Y)rsquo

軟體取得

6

147

5請選擇lsquoNextrsquo

軟體取得

7

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 2: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Introduction

2

應用領域

高科技運算程式解決方案 Technical Computing

控制設計 Control Design

訊號處理及通訊 Signal Processing and

Communications

影像處理 Image Processing

測試及量測 Test Measurement

生物運算 Computational Biology

財務模型及分析 Financial Modeling and Analysis

教育專區 Education

147

Outline

3

1

2

3

Fundamentals of MATLAB

Plotting

Simulink

4 Implemetation

5 Summary

147

1計中網頁(httpsoftbankccntuedutwUser2html)

2使用方式第一次使用首先點選右下方lsquo安裝驅動軟體rsquo非第一次使用請直接跳至第13項

軟體取得

4

147

3請選擇lsquo從程式目前所在位置執行這個程式(R)lsquo後再按確定鍵

軟體取得

5

147

4請選擇lsquo是(Y)rsquo

軟體取得

6

147

5請選擇lsquoNextrsquo

軟體取得

7

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 3: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Outline

3

1

2

3

Fundamentals of MATLAB

Plotting

Simulink

4 Implemetation

5 Summary

147

1計中網頁(httpsoftbankccntuedutwUser2html)

2使用方式第一次使用首先點選右下方lsquo安裝驅動軟體rsquo非第一次使用請直接跳至第13項

軟體取得

4

147

3請選擇lsquo從程式目前所在位置執行這個程式(R)lsquo後再按確定鍵

軟體取得

5

147

4請選擇lsquo是(Y)rsquo

軟體取得

6

147

5請選擇lsquoNextrsquo

軟體取得

7

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 4: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

1計中網頁(httpsoftbankccntuedutwUser2html)

2使用方式第一次使用首先點選右下方lsquo安裝驅動軟體rsquo非第一次使用請直接跳至第13項

軟體取得

4

147

3請選擇lsquo從程式目前所在位置執行這個程式(R)lsquo後再按確定鍵

軟體取得

5

147

4請選擇lsquo是(Y)rsquo

軟體取得

6

147

5請選擇lsquoNextrsquo

軟體取得

7

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 5: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

3請選擇lsquo從程式目前所在位置執行這個程式(R)lsquo後再按確定鍵

軟體取得

5

147

4請選擇lsquo是(Y)rsquo

軟體取得

6

147

5請選擇lsquoNextrsquo

軟體取得

7

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 6: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

4請選擇lsquo是(Y)rsquo

軟體取得

6

147

5請選擇lsquoNextrsquo

軟體取得

7

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 7: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

5請選擇lsquoNextrsquo

軟體取得

7

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 8: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

6請選擇lsquoI accept the terms in the license agreementlsquo後按lsquoNextrsquo

軟體取得

8

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 9: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

7請選擇lsquoNextrsquo

軟體取得

9

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 10: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

8預設值(Cache Size為 2048MB)建議改為(10000MB)

請選擇lsquoNextrsquo直到install畫面出現

軟體取得

10

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 11: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

9請選擇lsquoInstallrsquo開始安裝

軟體取得

11

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 12: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

10非第一次使用

待下載啟動程式碼完成(右下角顯示100)即會開

啟應用程式

安裝軟體時需使用擁有管理者(Administrator)權

限的帳戶

注意事項

1此為sbquo串流‛(stream)程式碼到PC執行的方式於

第一次使用新功能時需下載程式碼 請耐心等候

2若您的個人電腦已安裝相同應用程式 建議先解除

該軟體的安裝

3若有安裝錯誤訊息出現請跳過該訊息

軟體取得

12

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 13: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 什麼是 MATLAB

ndash MATrix LABoratory

ndash 以矩陣為運算基礎的數學軟體

ndash 直譯式的數學程式語言

ndash 提供完備的數學函數且能讓使用者定義自己的函數

ndash 提供矩陣運算數值分析統計分析訊號處理圖形繪製(2D3D)helliphellip等功能

MATLAB 簡介

13

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 14: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

MATLAB Interface

14

Workspace

Command

History

Current

Folder

Details

Command

Window

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 15: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Examplegtgt (52+35)5

ans =

27000

Scalar Arithmetic Operations

15

Symbol Operation MATLAB Form

^ exponentiation ab a^b

multiplication ab ab

right division ab = ab

left division ab = ab

+ addition a + b a+b

- subtraction a ndash b a-b

a

bb

a

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 16: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Order of Precedence

16

Precedence Operation

First Parentheses evaluated starting with the innermost pair

Second Exponentiation evaluated from left to right

Third Multiplication and division with equal precedence (left to right)

Fourth Addition and subtraction with equal precedence (left to right)

bull Examplegtgt 5^22

ans =

50

gtgt 52^2

ans =

20

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 17: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 直接列出矩陣內的元素產生矩陣

ndash 用逗號 () 或空白區隔同一列的元素

ndash 用分號 () 或 Enter 鍵代表一列的結束

ndash 矩陣的開始和結束使用中括號 ([]) 表示

矩陣的基本資料結構

17

bull Example

gtgt A=[1 2 3]

A =

1 2 3

gtgt B=[1 2 3 4 5 6]

B =

1 2 3

4 5 6

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 18: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 直接列出矩陣內的元素產生矩陣

ndash 或使用下列描述法構成

X=起始值增加值結束值

矩陣的基本資料結構 (cont‟d)

18

bull Example

gtgt A=[110]

A =

1 2 3 4 5 6 7 8 9 10

gtgt A=[1210]

A =

1 3 5 7 9

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 19: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 利用 MATLAB 的敘述或函式產生

矩陣的基本資料結構 (cont‟d)

19

bull Example

gtgt A=ones(34)

A =

1 1 1 1

1 1 1 1

1 1 1 1

gtgt B=linspace(1104)

B =

1 4 7 10

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 20: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

矩陣的索引或下標

Ref httpwwwcsnthuedutw~jang第九章矩陣的處理與運算

20

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 21: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Description

ans Temporary variable containing the most recent answer

eps Specifies the accuracy of floating point precision

ij The imaginary unit

Inf Infinity infin

NaN Indicates an undefined numerical result (Not a Number)

pi The number π

Predefined Constants

21

1

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 22: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 第一個字母必需是英文字母

bull 字母間不可留空格

bull 字母大小寫有異

bull 最多只能有 31 個字母MATLAB 會忽略多餘字母(在MATLAB 第 4 版則是 19 個字母)

bull MATLAB 在使用變數時不需預先經過變數宣告(Variable Declaration)的程序而且所有數值變數均以預設的 double 資料型式儲存

變數命名規則與使用

bull Example

PSE123 (O)3PSE21 (X)PSE_123(O)PSE-123 (X) 22

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 23: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Symbol Operation Form Example

+ Scalar-array addition A+b [63]+ 2 =[8 5]

- Scalar-array subtraction A-b [63]- 2 =[911]

+ Array addition A+B [63]+[38] =[911]

- Array subtraction A-B [63]-[38] =[3-5]

Matrix multiplication AB [12][34] =[11]

Matrix left division x=A-1B AB [12][10] =[0 5]

Array multiplication AB [32][24] =[6 8]

Array right division AB [48][24] =[2 2]

Array left division AB [24][48] =[2 2]

^ Array exponent A^B [35]^2 =[925]

2^[35] =[832]

[32]^[23] =[9 8]

Matrix operations

23

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 24: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Example

Relational operators

24

Relational Operator Meaning

lt Less than

lt= Less than or equal to

gt Greater than

gt= Greater than or equal to

== Equal to

~= Not equal to

gtgt x = [ 6 3 9]

gtgt y = [14 2 9]

gtgt z = (x lt y)

z =

1 0 0

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 25: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Example

bull 矩陣的邏輯運算

ampAnd 運算(=and)

|Or 運算(=or)

~Not 運算(=not)

any任何一個元素不為零

all所有元素都不為零

矩陣的邏輯運算

25

gtgt X=[0 1 2 3]

X = 0 1 2 3

gtgt any(X)

ans = 1

gtgt any(X==4)

ans = 0

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 26: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Description

find(x) Computes an array containing indices of nonzero elements of array x

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 times n matrix

size(A) Returns a row vector [m n] containing the sizes of the m times n array

max(A) Returns a row vector containing largest element in each column of A

min(A) Same as max(A) but returns minimum values

Inv(A) Return the inverse of the square matrix A

det(A) Return the determinant of the square matrix A

eig(A) Returns a vector of the eigenvalues of matrix A

sort(A) Sorts each column of array A in ascending order and returns an array the same size as A

sum(A) Sums the elements in each column of array A and returns a row vector containing the sums

Some Useful Array Functions

26

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 27: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

zeros(mn) 維度為mxn 元素全為0的矩陣

ones(mn) 維度為mxn 元素全為1的矩陣

eye(n) 維度為nxn的identity矩陣

rand(mn) 維度為mxn於[01]均勻分佈的亂數矩陣

randn(mn) 維度為mxn於[01]高斯分佈的亂數矩陣

[] 空矩陣

diag 對角矩陣

linspace 產生線性的空間向量

常見特殊矩陣

27

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 28: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

=指定(Assign)運算 (ex B=A)

矩陣轉置 (ex B=A)

代表上一層目錄 (ex cd )

繼續代表指令未完接到下一列

元素分隔符號

代表命令結束且不印出執行結果

註解列

Special Characters

28

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 29: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 在 MATLAB 運算過程可以隨時改變每一個矩陣的維度以容納新的資料但是每一次增大矩陣的容量時MATLAB 就必須要向電腦的作業系統索取記憶體因此會造成程式執行效率的降低而且造成記憶體的分散使用現象(Memory Segmentation)此種由於記憶體的動態配置而造成的分散使用現象可能導致實際雖仍有充足的記憶體但卻未有連續空間以處理較大矩陣的現象

bull 基於以上種種原因若預先知道使用矩陣的維度大小則最好實施矩陣的預先配置(Pre-allocation)可用的指令有 zerosonescell

(用於配置異值陣列)及 struct(用於配置結構陣列)等例如欲計算矩陣A 的 n 次方的行列式其中 n = 1~100可輸入如下

Pre-allocation

29

A = [1 2 3 4 5 6 7 8 9]

det_value = zeros(1 100)

for i = 1100

det_value(i) = det(A^i)

end

Example

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 30: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Workspace 中變數的保存方式

ndash save將 workspace 中的變數存到磁碟上

ndash load由磁碟上的資料檔載入變數到

workspace 中

bull 不加任何選項(Options)時save 指令會將工作空間內

的變數以二進制(Binary)的方式儲存至副檔名為 mat 的

檔案

工作空間與變數的儲存及載入

30

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 31: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 使用 save 保存變數

save將所有變數以二進位格式存至 ldquomatlabmatrdquo中

save fname將所有變數存至rdquofnamematrdquo中

save fname X Y將變數 X 與 Y 存至rdquofnamematrdquo中

save fname X -ascii使用 8 位數文字格式將變數X 存至rdquofnamerdquo中

save fname X -ascii -double使用 16 位數文字格式將變數 X 存至rdquofnamerdquo中

save nametxt X -ascii -double ndashtabs 使用 16 位數文字格式將變數 X 存至rdquofnamerdquotxt的文字檔中

工作空間與變數的儲存及載入(cont‟d)

31

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 32: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 使用 load 載入變數

load由『matlabmat』中載入所有變數

load fname由『fnamemat』中載入所有變數

load fname X Y由『fnamemat』中載入變數 X 與 Y

load fname -ascii由文字檔『fname』中載入變數

load fnametxt由文字檔『fnametxt』中載入變數

工作空間與變數的儲存及載入(cont‟d)

32

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 33: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Description

clc Clears the command window

clear Removes all variables from memory

clear var1 var2 Removes var1 and var2 from memory

exist(rsquonamersquo) Determine if a file or variable exists having the name rsquonamersquo

quit Stop MATLAB

Colon generates an array having regularly spaced elements

Comma separates elements of an array

Semicolon suppresses screen printing also denotes a newrow in an array

Ellipsis continues a line to delay execution

Commands for Managing the

Work Session

33

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 34: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull MATLAB 程式的基本M-file

bull M-file 的特性

ndash 是純文字文件(只要延伸檔名維持 m)

ndash 任何 MATLAB 指令都可以出現在 M-file 中

bull M-file 的種類

ndash Script (命令稿命令巨集)

ndash Function (函式)

MATLAB 下的程式寫作

34

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 35: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

開啟M-File

35

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 36: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Script

ndash 用來連續執行一連串的指令

ndash 所有執行中使用或產生的變數皆存在於 workspace因此變數容易互相覆蓋而造成程式錯誤

ndash 沒有輸入與輸出變數

bull Function

ndash 用來定義一個自訂函式

ndash 除了全域變數(global variables)所有執行中使用或產生的變數皆不存在於 workspace因此不會和MATLAB 基本工作空間的變數相互覆蓋

ndash 可以有輸出與輸入變數

MATLAB 下的程式寫作 (cont‟d)

36

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 37: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Example

MATLAB 下的程式寫作

37

第一列為函數定義列(Function Definition Line)bull定義函數名稱(FindRoots最好和檔案的檔名相同)bull輸入引數( [x1 x2] )bull輸出引數(abc)bullfunction為關鍵字

第二列開始為函數主體(Function Body)bull描述函數運算過程並指定輸出引數的值

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 38: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

[Output1 Output2 hellip] = CommandName(input1

input2 hellip)

CommandName built-in or user-defined function

呼叫Function

38

FindRootsmfunction [x1 x2] = FindRoots(abc)

x1=(-b+(b^2-4ac)^05)(2a)

x2=(-b-(b^2-4ac)^05)(2a)

gtgt a=1

gtgt b=3

gtgt c=1

gtgt [x1 x2] =FindRoots(abc)

x1 =

-10000 + 14142i

x2 =

-10000 - 14142i

Example

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 39: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 次函數(sub-function)一個M 檔案可以有一個以上的次函數

次函數

39

Cal_abcm

function [a b c] = Cal_abc(H

a=H^3

b=H3

c=H-3

gtgt v=1

gtgt [x1 x2] = TEST(v)

x1 =

12573

x2 =

-15907

Example

TESTmfunction [x1 x2] = TEST(H)

[a b c]= Cal_abc(H)

[x1 x2] = FindRoots(abc)

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 40: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 全域變數(global variable)此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用

全域變數 (global variable)

40

Antoinem

function p_vap=antoine(t)

global a b c

p_vap=exp(a-b(t+c))

Example

TESTmglobal a b c

a=183036

b=381644

c=-4613

for i=111

t=3732+10(i-1) t in Kelvin

psat(i)=antoine(t) psat in mmHg

end

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 41: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 程式的流程控制(Flow Control)

ndash 迴圈指令(Loop Command)

bull for helliphellip end

bull while helliphellip end

ndash 條件指令(Branching Command)

bull if hellip elseif hellip else hellip end

bull switch hellip case hellip otherwise hellip end

MATLAB 下的流程控制

41

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 42: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull for 迴圈

ndash 語法 1

for 變數=向量

運算式

end

ndash 語法 2

for 變數=矩陣

運算式

end

MATLAB 下的流程控制 - for

42

gtgtx=1

gtgt for i=15

gtgt x=xi

gtgt end

gtgt disp(x)

120

gtgt x=[1 3 2 4]

gtgt for i=x

gtgt fprintf(dti)

gtgt end

1 2 3 4

Example

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 43: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull while 迴圈

ndash 語法

while 條件式

運算式

end

MATLAB 下的流程控制 - while

43

1+ ε lt 1

e= 1

while (1+e) gt 1 判斷式成立e = e2

end

e = e2

Example

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 44: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull if 條件指令ndash 語法

if 條件式一

運算式一

elseif 條件式二

運算式二

elseif 條件式三

運算式三

else

運算式四

end

MATLAB 下的流程控制 - if

44

if x gt 10

y = log(x)

elseif x gt= 0

y = sqrt(x)

else

y = exp(x) - 1

end

Example

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 45: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull switch 條件指令ndash 語法

switch 運算式

case 值一

運算式一

case 值二

運算式二

otherwise

運算式三

end

MATLAB 下的流程控制 ndash switch

45

for month=112

switch month

case 345

season=Spring

case 678

season=Summer

case 91011

season=Autumn

otherwise

season=Winter

end

fprintf(Month d is snmonthseason)

End

Result

Month 1 is Winter

Month 2 is Winter

Month 3 is Spring

Month 4 is Spring

hellip

Example

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 46: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull break Terminate execution of for or while

loop

bull return Return to invoking function

MATLAB 下的流程控制

46

detm

function d = det(A)

DET det(A) is the determinant of A

if isempty(A)

d = 1

return

else

end

for i = 11000

if prod(1i) gt 1e10

break 跳出迴圈end

end

disp(i)

14

Example

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 47: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

clear all

A=[1 2 3 4]

B(1)=A(1)C(1)=A(1)

for i=2length(A)

if A(i)gt=3

B(1i)=A(i)+C(i-1)

else

B(1i)=A(i)+B(i-1)

end

C(1i)=myfun(B(i))

end

Ans=BC

Exercise

47

myfunm

function C=myfun(B)

while B gt 2

B=B-1

end

C=B^2

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 48: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Plotting

48-3

-2-1

01

23

-2

0

2

-10

-5

0

5

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 49: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Description

axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes

fplot(rsquostringrsquo xmin xmax]) Performs intelligent plotting of functions where rsquostringrsquo is a text string that describes the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable The range of the dependent variable can also be specified In this case the syntax is fplot (rsquostringrsquo xmin xmax ymin ymax])

grid Displays gridlines at the tick marks corresponding to the tick labels Type grid on to add gridlines type grid off to stop plotting gridlines When used by itself grid switched this feature on or off

plot(xy) Generates a plot of the array x on rectilinear axes

legend(leg1leg2 ) Creates a legend using the strings leg1 leg2 and so on and specifies its placement with the mouse

print Prints the plot in the figure window

title(text) Puts text in a title at the top of a plot

xlabel(text) Adds a text label to the x-axis(the abscissa)

ylabel(text) Adds a text label to the y-axis(the ordinate)

hold Freezes the current plot for subsequent graphics commands

subplot(mnp) Splits the figure window into an array of subwindows with m rows andn columns and directs the subsequent plotting commands to the pth subwindow

text(xytext) Places the string text in the figure window at point specified by coordinates x y

Some MATLAB Plotting Commands

49

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 50: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull plot -- 繪圖指令的根本語法plot(XY format)將向量 Y 對向量 X 做圖

二維基本繪圖簡介

50

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt plot(X Y bx-)

bdquocolor marker line-type)

Example

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 51: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Data markers Line types Colors

Dot () Solid line - Black k

Asterisk () Dashed line -- Blue b

Cross (times) x Dash-dotted line - Cyan c

Circle () o Dotted line Green g

Plus sign (+) + Magenta m

Square () s Red r

Diamond () d White w

Five-point star () p Yellow y

Data Markers Line Types and

Colors

51

Tips

Command Linehelp plot

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 52: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

0 2 4 6 8-1

-05

0

05

1Y vs X

X

f(X

)

sin(X)

圖形標題與座標軸

52

X=[0012pi]

Y=sin(X)

plot(X Y b--linewidth3)

title(Y vs Xfontsize15)

xlabel(Xfontsize15)

ylabel(f(X)fontsize15)

legend(sin(X)fontsize15)

set(gcafontsize15)

Example

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 53: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

1 使用 plot 的第三種形式一次畫出多個數對

2 使用 hold 將圖形「固定」住重疊多個數對的繪圖結果

3 使用 subplot 分割繪圖視窗同時呈現多個子圖形

單一圖片呈現多個圖形

53

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 54: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull plot -- 繪圖指令的根本語法plot(X1Y1 format1 X2Y2 format2)將 Yi 對 Xi

以 formati 做圖

單一圖片呈現多個圖形 - plot

54

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt plot(X Y bx- X Z r)

Example

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 55: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 使用 hold 重疊多個數對圖形

單一圖片呈現多個圖形 - hold

55

gtgtX=[0012pi]

gtgtY=sin(X)

gtgtZ=cos(X)

gtgtplot(X Y b--)

gtgthold on

gtgtxlabel(X)

gtgtylabel(f(X))

gtgtplot(X Z r)

gtgttext(020sin(X))

gtgttext(05pi+020cos(X))

Example

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 56: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 使用 subplot 分割視窗呈現數個子圖形

單一圖片呈現多個圖形 - subplot

56

gtgt X=[0012pi]

gtgt Y=sin(X)

gtgt Z=cos(X)

gtgt subplot(211)

gtgt plot(X Y b--)

gtgt xlabel(X)

gtgt ylabel(sin(X))

gtgt subplot(212)

gtgt plot(X Z r)

gtgt xlabel(X)

gtgt ylabel(cos(X))

Example

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 57: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Plot tools

57

Show plot tool Hide plot tool

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 58: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Enhance your figure

58

Generate Code

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 59: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

t = 0pi5010pi

plot3(sin(t)cos(t)t)

grid on

axis square

三維基本繪圖簡介 ndash line plot

59

-1

-05

0

05

1

-1

-05

0

05

1

0

10

20

30

40

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 60: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

meshgridGenerate X and Y arrays for 3-D plots

[XY] = meshgrid(-31253)

Z = peaks(XY)

mesh meshc meshz Mesh plots

mesh(XYZ)

axis([-3 3 -3 3 -10 5])

三維基本繪圖簡介 ndash mesh plot

60-3-2

-10

12

3

-2

0

2

-10

-5

0

5

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 61: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Simulink

61

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 62: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 什麼是 Simulink

ndash MATLAB 提供的一個 toolbox

ndash 應用於動態系統模擬

ndash 提供 GUI使動態系統的建立如同畫方塊圖

(Block Diagram)

Simulink 簡介

62

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 63: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 啟動 Simulink

ndash 直接在 command window 鍵入 「simulink」

ndash 使用工具列的 Simulink 按鈕

啟動 Simulink

63

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 64: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Simulink 的外觀

啟動 Simulink

64

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 65: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 動態模型的建立步驟

ndash 開啟一個空白的模型(Model)

ndash 開啟適當的 Library 視窗找出所有需要的Block將該 Block 拖入或複製至空白模型視窗

ndash 用滑鼠雙擊各 Block 開啟對話視窗適當設定各 Block 所需的參數

ndash 利用滑鼠連接各個 Block建立完整的動態系統

動態模型的建立

65

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 66: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

動態模型的建立

66

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 67: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Symbolic calculation

67

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 68: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull subs(Eoldnew)可以將算式 E 中 old 的部分以new取代其中 old 這個部分可以是符號變數或者是符號表示式並且 new 這個部分可以是符號變數符號表式矩陣數值的值或者是數值的矩陣

subs函數

68

gtgtsyms x y

gtgtE = x^2+6x+7

gtgtF = subs(Exy)

F =

y^2+6y+7

gtgt F = subs(Ex5)

F =

62

Example

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 69: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

solve 函數

69

gtgteq1 = rsquox+5=0rsquo

gtgtsolve(eq1)

ans =

-5

gtgtsolve(rsquox+5=0rsquo)

ans =

-5

gtgtsyms x

gtgtsolve(x+5)

ans =

-5

有三種使用solve函數的方式例如要求解方程式 x + 5 = 0

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 70: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

limit函數

函數 limit(E) 可以用來求出當 x rarr 0的時候 E 的極限

gtgtsyms a x

gtgtlimit(sin(ax)x)

ans =

a

另外limit(Eva)這個形式可以用來求出當u rarr a 時的極限舉例來說

gtgtsyms h x

gtgtlimit((x-3)(x^2-9)3)

ans =

16

gtgtlimit((sin(x+h)-sin(x))hh0)

ans =

cos(x)

70

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 71: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Symbolic Calculation (diff int)

71

syms x

f=sin(x)

c=diff(f)

d=diff(f2)

c_value=subs(c2)

d_value=subs(d2)

c =

cos(x)

d =

-sin(x)

c_value =

-04161

d_value =

-09093

syms x y

f=sin(x)+cos(y)

c=diff(fx)

c2=diff(fx2)

d=diff(fy)

d2=diff(fy2)

c =

cos(x)

c2 =

-sin(x)

d =

-sin(y)

d2 =

-cos(y)

syms x

f=-2x(1+x^2)^2

c=int(f)

d=int(f01)

c =

1(1+x^2)

d =

-12

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 72: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

gtgtsyms b t

gtgtlaplace(t^3)

ans =

6s^4

gtgtlaplace(exp(-bt))

ans =

1(s+b)

gtgtlaplace(sin(bt))

ans =

b(s^2+b^2)

拉氏轉換

72

Example

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 73: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

gtgtsyms b s

gtgtilaplace(1s^4)

ans =

16t^3

gtgtilaplace(1(s+b))

ans =

exp(-bt)

gtgtilaplace(b(s^2+b^2)

ans =

sin(bt)

反拉氏轉換

73

Example

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 74: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

gtgtsyms k

gtgtA = [0 1-k -2]

gtgtpoly(A)

ans =

x^2+2x+k

gtgtsolve(ans)

ans =

[ -1+(1-k)^(12) ]

[ -1-(1-k)^(12) ]

特徵方程式以及特徵根

74

Example

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 75: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical differentiation

75

True Slope

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 76: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical Differentiation(diff)

76

d = diff(x)

= [x(2) minus x(1) x(3) minus x(2) x(n) minus x(n minus 1)]

x=0011

y=[05 06 07 09 12 14 17 20 24 29 35]

dx=diff(x)

dy=diff(y)

dydx=diff(y)diff(x)

dydx =

10000 10000 20000 30000 20000 30000 30000 40000 50000

60000

Example

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 77: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical Differentiation Functions

77

Command Description

b = polyder(p) Returns a vector b containing the coefficients of the derivative of the polynomial represented by the vector p

b=polyder(p2p1) Returns a vector b containing the coefficients of the derivative of the polynomial that is the product of the polynomials represented by p2 and p1

[nd]=polyder(p2p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2p1 where p2 and p1 are polynomials

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 78: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical Differentiation Polynomial Derivatives

78

p1 = [52] p2 = [104-3]

der2 = polyder(p2)

prod = polyder(p2p1)

[numden] = polyder(p2p1)

der2 =

20 4

prod =

150 80 -7

num =

50 40 23

den =

25 20 4

1

2

2

2

3 2

1 2

21 2

2

2 1

2

5 2

10 4 3

20 4

50 40 7 6

150 80 7

( ) 50 40 23

25 20 4

p x

p x x

dpx

dx

p p x x x

dp px x

dx

d p p x x

dx x x

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 79: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical integration

79

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 80: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical Integration

80

Command Description

trapz(xy) Uses trapezoidal integration to compute the integral of y with respect to x where the array y contains the function values at the points contained in the array x

quad(rsquofunctionrsquoabtol) Uses an adaptive Simpsonrsquos rule to compute theintegral of the function rsquofunctionrsquo with a as the lower integration limit and b as the upper limit The parameter tol is optional tol indicates the specified error tolerance

quad1(rsquofunctionrsquoabtol) Uses Lobatto quadrature to compute the integral of the function rsquofunctionrsquo The rest of the syntax is identical to quad

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 81: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical Integration

81

x = linspace(0 pi 10) ans =

y = sin(x) 19797

trapz(x y)

x = linspace(0 pi 100) ans =

y = sin(x) 19998

trapz(x y)

x = linspace(0 pi 1000) ans =

y = sin(x) 20000

trapz(x y)

00sin( ) cos( ) cos(0) cos( ) 2x dx x

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 82: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Interpolation

82

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 83: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Polynomial Interpolation Functions(1D)

83

y_est=interp1(xyx_estmethod)

This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - linear interpolation

spline - piecewise cubic spline interpolation (SPLINE)

pchip - piecewise cubic Hermite interpolation (PCHIP)

cubic - same as rsquopchiprsquo

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 84: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Polynomial Interpolation Functions(2D)

84

z_est=interp2(xyzx_esty_estrsquomethodrsquo)This command specifies alternate methods The default is linear interpolationAvailable methods are

nearest - nearest neighbor interpolation

linear - bilinear interpolation (or bilinear)

spline - cubic spline interpolation (SPLINE)

cubic - bicubic interpolation

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 85: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Curve fitting (regression)

85

0 02 04 06 08 1 12 14 16 18 20

1

2

3

4

5

6Input data

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 86: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Description

p = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers

[ps mu] = polyfit(xyn) Fits a polynomial of degree n to data described by the vectors x and y where x is the independent variable Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers and a structure s for use with polyval to obtain error estimates for predictions The optional output variable mu is two-element vector containing the mean and standard deviation of x

Functions for Polynomial Regression

86

The linear function y = mx + b gives a straight line when

plotted on rectilinear axes Its slope is m and its intercept is b

rarr p = polyfit(x y 1)

Example

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 87: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Curve Fitting Tools

Create data set

Choose model

87

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 88: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Curve Fitting Tools (cont‟d)

88

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 89: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Minimization (optimization)

89

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 90: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

minimum of near (00)

function f = f146(x)

f = x(1)exp(-x(1)^2-x(2)^2)

end stored in f145m

fminsearch(f146[00])

[f fval] = fminsearch(‟f146‟[00])

ans =

-07071 00000

Minimizing A Function of Variables

(fminsearch)

90

2 2x yf xe

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 91: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull fmincon find minimum of constrained nonlinear

multivariable function

bull fminbnd find minimum of single-variable function on

fixed interva

bull Isqlin constrained linear least-squares problems

Equation

bull lsqnonlin Solve nonlinear least-squares (nonlinear

data-fitting) problems

bull quadprog Solve quadratic programming problems

Other Built-in Functions

91

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 92: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Optimization Tool

92

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 93: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Solving algebraic equation

93

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 94: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Equation Type solver

Polynomial roots roots

continuous function of one variable fzero

nonlinear equations fsolve (fminsearchhellip)

Finding Roots of Equations

94

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 95: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull roots polynomial roots

ndash syntaxx = roots([c1 c2 c3hellip cn+1])

roots

95

1 2

1 2 3 1n n n

n nc x c x c x c x c

p = [1 -6 -72 -27]

r = roots(p)

r =

121229

-57345

-03884

3 26 72 27 0x x x Example

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 96: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Description

poly(r) Computes the coefficients of the polynomial whose rootsare specified by the array r The resulting coefficients arearranged in descending order of powers

polyval(ax) Evaluates a polynomial at specified values of its independentvariable x The polynomialrsquos coefficients of descendingpowers are stored in the array a The result is the same sizeas x

roots(a) Computes an array containing the roots of a polynomialspecified by the coefficient array a

Some Polynomial Functions

96

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 97: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

x3 - 7x2 + 40x -34 =0

a = [1 -7 40 -34]

roots(a)

a =

1 -7 40 -34

ans =

3000 + 5000i

3000 - 5000i

1000

Polynomial Roots

97

roots = 1 3 plusmn 5i

r = [1 3+5i 3-5i]

poly(r)

r =

100 300+500i 300-500i

ans =

1 -7 40 -34

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 98: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull fzero find root of continuous function of one variable

ndash syntax

x = fzero(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

fzero 函數

98

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 99: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example - fzero

99

0 1 2 3 4 5 6 7 8 9 10-15

-1

-05

0

05

1

15

x

sin

(x)

- co

s(x

)

func01m

function f=func01(x)

f = sin(x) - cos(x)

gtgt fzero(func01[0 3])

ans =

07854

gtgt fzero(func01[3 6])

ans =

39270

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 100: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull fsolve 解聯立方程式ndash 語法

x = fsolve(FUN x0)

x解

FUN定義問題的 function M-file 檔名

x0初始猜值矩陣

ndash Reamarkfsolve() 是 optimization toolbox 的指令

fsolve 函數

100

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 101: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example - fsolve

101

function F=func01(X)

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

F=AX-b

x0=[1 1 1]

x=fsolve(func01x0)

x= -04000

-11077

20308

Use help fsolve for details

1 7 5 1 2

2 3 4 2 4

9 6 8 3 5

x

x

x

A=[1 7 5 2 3 49 6 8]

b=[ 2 46]

c=inv(A)b

x= -04000

-11077

20308

11 1 7 5 2

2 2 3 4 4

3 9 6 8 5

x

x

x

Method 1 Method 2

Example

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 102: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

Van de Vusse reaction in an isothermal CSTR

102

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 103: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example

103

vdv_sol_adm

x0=[21117]

k1=56

k2=53

k3=16

fov=47

caf=10

options=optimset(Displayiter

)

[x]=fsolve(vdv_aex0options

k1k2k3fovcaf)

cas=x(1)

cbs=x(2)

vdv_adm

function F = vdv_ae(xk1k2k3fovcaf)

F = [fov(caf-x(1))-k1x(1)-k3(x(1)^2)

-fovx(2)+k1x(1)-k2x(2)]

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 104: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Debug

104

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 105: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Debug mode

breakpoint

Run vdv_sol_aem

105

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 106: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Debug mode (cont‟d)

ContinueStep

106

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 107: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Solving ODE by m-file

107

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 108: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull 解 ode 可用的 functionode23() ode113() ode15s() ode23s()

ode23t() ode23tb() ode45()

bull 基本語法(以 ode45() 為例)

[TY] = ode45(FTSPANY0OPTIONS)

or [TY] = ode45(FTSPANY0OPTIONS)

T時間

Fode function M-file 定義檔檔名

TSPAN積分時間

Y0初始值

OPTIONS特殊選項

P1 P2 hellip其餘欲傳給 ode function M-file 的參數

用 MATLAB 解 ODE

108

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 109: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example 1

109

function dy = rigid(ty)

dy = zeros(31) a column vector

dy(1) = y(2) y(3)

dy(2) = -y(1) y(3)

dy(3) = -051 y(1) y(2)

1 2 3 1

2 1 3 1

3 1 2 1

(0) 0

(0) 0

051 (0) 0

y y y y

y y y y

y y y y

rigidm

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 110: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

gtgt[tY] = ode45(rigid[0 12][0 1 1])

gtgtplot(TY(1)-TY(2)-TY(3))

Example 1 (cont‟d)

1100 2 4 6 8 10 12-1

-08

-06

-04

-02

0

02

04

06

08

1

t

Y

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 111: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example 2

111

先將二階化成標準格式令

vdp1m

function dy = vdp1(t y)

mu=1

dy = [ y(2)

mu(1-y(1)^2)y(2)-y(1)]

Command Lines

ode45(vdp1 [0 25] [3 3])

or

ode45(vdp1 [0 25] [3 3])

2(1 ) 0y y y y

1 2y y y y

1 2

2

2 1 2 1(1 )

y y

y y y y

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 112: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example 3 ndash VDV reaction

112

function xdot = vdv_ode(tx)

ca=x(1)

cb=x(2)

k1=56

k2=53

k3=16

fov=47

caf=10

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

xdot=[dcadtdcbdt]

vdvodem

2

1 3

1 2

1 1

1 2 3

1

( )

Parameters

5 5 1 molmin min

6 3 6 L min

Inputs

4min 10molL

7

A

Af A A A

B

B A B

Af

dC FC C k C k C

dt V

dC FC k C k C

dt V

k k k

FC

V

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 113: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Example 3 (cont‟d)

113

x0=[21117]

tspan=[0 5]

[tx]=ode45(vdv_odetspanx0)

subplot(211)

plot(tx(1))

xlabel(t)

ylabel(ca)

subplot(212)

plot(tx(2))

xlabel(t)

ylabel(cb)

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 114: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Solving ODE using dee

114

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 115: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147115

Command Line

dee

A window named dee will appear

dee 啟動指令

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 116: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147116

模型建立

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 117: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

執行指令與作圖

117

0 05 1 15 2 25 3 35 4 45 52

25

3

t

ca

0 05 1 15 2 25 3 35 4 45 509

1

11

12

t

cb

k1=56

k2=53

k3=16

fov=47

caf=10

x0=[21117]

sim(vdv_sim_4[0 5])

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 118: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Solving ODE using S-function

118

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 119: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147119

Enter search term

Constant

S-function

Example ndash VDV reaction

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 120: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Line

open sfuntmplm

sfuntmplm will appear

120

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 121: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

vdv_sfunm

121

function [sysx0strts] = vdv_sfun(txuflagx0)

switch flag

case 0

[sysx0strts]=mdlInitializeSizes(x0)

case 1

sys=mdlDerivatives(txu)

case 2

sys=mdlUpdate(txu)

case 3

sys=mdlOutputs(txu)

case 4

sys=mdlGetTimeOfNextVarHit(txu)

case 9

sys=mdlTerminate(txu)

otherwise

DAStudioerror(SimulinkblocksunhandledFlag num2str(flag))

end

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 122: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

function [sysx0strts]=mdlInitializeSizes(x0)

sizes = simsizes

sizesNumContStates = 2

sizesNumDiscStates = 0

sizesNumOutputs = 2

sizesNumInputs = 2

sizesDirFeedthrough = 0

sizesNumSampleTimes = 1 at least one sample time is needed

sys = simsizes(sizes)

str = []

ts = [0 0]

vdv_sfunm (cont‟d)

122

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 123: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

function sys=mdlDerivatives(txu)

ca=x(1)

cb=x(2)

fov=u(1)

caf=u(2)

k1=56

k2=53

k3=16

dcadt=fov(caf-ca)-k1ca-k3(ca^2)

dcbdt=-fovcb+k1ca-k2cb

sys = [dcadtdcbdt]

function sys=mdlUpdate(txu)

sys = []

vdv_sfunm (cont‟d)

123

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 124: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

function sys=mdlOutputs(txu)

sys = [x(1)x(2)]

function sys=mdlGetTimeOfNextVarHit(txu)

sys = []

function sys=mdlTerminate(txu)

sys = []

vdv_sfunm (cont‟d)

124

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 125: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147125

1

2

34

Example ndash VDV reaction (contrsquod)

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 126: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147126

Command Line

x0=[21117]

Example ndash VDV reaction (contrsquod)

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 127: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147127

subplot(211)

plot(tca)

xlabel(t)

ylabel(ca)

subplot(212)

plot(tcb)

xlabel(t)

ylabel(cb)

Example ndash VDV reaction (contrsquod)

sfun_plotm

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 128: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147128

Step

MV step change

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 129: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Command Line

x0=[31117]

Start Simulation

129

Reach New Steady

State

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 130: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147130

Refine Simulink file

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 131: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147131

Create Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 132: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147132

Mask Subsystem

in mouse right click menu

Refine Simulink file (contrsquod)

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 133: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147133

Add

Refine Simulink file (contrsquod)

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 134: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147134

Right double click on subsystem will appear the following window

Refine Simulink file (contrsquod)

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 135: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Simulating LTI model

135

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 136: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

LTI model 的建立

136

A=[-24048 0083333 -22381]

B=[7-1117]

C=[0 1]

D=[0]

vdv_ss=ss(ABCD)

num=[-1117 31472]

den=[1 46429 53821]

vdv_tf=tf(numden)

vdv_zpk=zpk(2817[-2238 -2405]-1117)

vdv_tf1=tf(vdv_ss)

vdv_zpk1=zpk(vdv_tf1)

vdv_tfd=c2d(vdv_tf1zoh)

vdv_tf2=tf(numdenInputdelay1)

[ysts]=step(vdv_tf)

plot(tsys)

[yiti]=impulse(vdv_tf)

plot(tiyi)

pole(vdv_tf)

tzero(vdv_tf)

0 05 1 15 2 25 3 35 4-01

0

01

02

03

04

05

06

0 05 1 15 2 25 3 35 4-12

-1

-08

-06

-04

-02

0

02

04

06

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 137: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

LTI model 進階分析

137

10-1

100

101

102

10-2

10-1

100

10-1

100

101

102

0

100

200

300

400

kc=1

figure(1)

bode(kcvdv_tf)

figure(2)

[magphasew]=bode(kcvdv_tf)

subplot(211)loglog(wsqueeze(mag))

subplot(212)semilogx(wsqueeze(phase))

[GmPmWgWp]=margin(magphasew)

nyquist(kcvdv_tf)

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 138: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Simulate LTI model using Simulink

138

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 139: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147139

Transfer Fcn

0 05 1 15 2 25 3 35 4 45 511

111

112

113

114

115

116

117

118

119

t

cb

Nonlinear

Linear

LTI model 的建立

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 140: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147140

Closed-loop simulation

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 141: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147141

PID Controller

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 142: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147142

Look Under

Mask

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 143: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Solving PDE

143

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 144: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical Methods for PDE(pdepe)

144

( ) ( ( )) ( )m m

x t x xc x t u u u x x b x t u u s x t u ux

2

( 0) 0 ( 1) 1

2 (0 )

1

t xxu u

B C u t u t

xI C u x

ff ff

fx

f

pdepe solves PDEs of the form

with boundary conditions

( ) ( ) ( ) 0

( ) ( ) ( ) 0

l l l x

r r r x

p x t u q x t b x t u u

p x t u q x t b x t u u

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 145: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

function [cbs] = eqn1(xtuDuDx)

EQN1 MATLAB function M-le that

species

a PDE in time and one space

dimension

c = 1

b = DuDx

s = 0

function [plqlprqr] = bc1(xlulxrurt)

BC1 MATLAB function M-le that

species boundary conditions

for a PDE in time and one space

dimension

pl = ul

ql = 0

pr = ur-1

qr = 0

Numerical Methods for PDE(pdepe)

145

function value = initial1(x)

INITIAL1 MATLAB function M-le

that species the initial condition

for a PDE in time and one space

dimension

value = 2x(1+x^2)

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 146: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

Numerical Methods for PDE(pdepe)

146

PDE1 MATLAB script M-le that solves and plots

solutions to the PDE stored in eqn1m

m = 0

x = linspace(0120)

t = linspace(0210)

Solve the PDE

u = pdepe(meqn1initial1bc1xt)

Plot solution

surf(xtu)

title(Surface plot of solution)

xlabel(Distance x)

ylabel(Time t)

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147

Page 147: MATLAB 2011 workshop/147 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權

147

bull Writing down before coding

bull Looking for help

bull Using recognizable name of variable

bull Checking matrix dimension

bull Checking loop and interation

Summary

147