Download presentation
Presentation is loading. Please wait.
1
Introduction of MATLAB©
MATLAB 2014 workshop Introduction of MATLAB© Speaker: Hsing-Yu Wang (王馨右) Date: 09/12/2014 Perhaps we should begin. Good afternoon, ladies and gentlemen. Thanks for coming. My name is Shih-Wei Liu. This afternoon I would like to present A Dynamic Model with Structured Recurrent Neural Network to Predict Blood Glucose in a patient with Type 1 Diabetes Mellitus. PSE Laboratory Department of Chemical Engineering National Taiwan University
2
Introduction 應用領域 高科技運算程式解決方案 Technical Computing 控制設計 Control Design
訊號處理及通訊 Signal Processing and Communications 影像處理 Image Processing 測試及量測 Test Measurement 生物運算 Computational Biology 財務模型及分析 Financial Modeling and Analysis 教育專區 Education
3
Fundamentals of MATLAB
Outline 1 Fundamentals of MATLAB 2 Plotting Here is my outline. This presentation is about 15 mins and will be divided into four parts. First of all, I will start off by filling you on the background to this field. Then I will elaborate on the methodology of this research. Next, I would like to report on the results of a case study. Finally, I will make a brief conclusion of my presentation today. 3 Implemetation 4 Summary
4
軟體取得 1.計中網頁( 2.使用方式:第一次使用首先點選APPShare,非第一次使用請直接跳至第13頁
5
軟體取得
6
軟體取得
7
軟體取得
8
軟體取得
9
軟體取得
10
軟體取得
11
軟體取得
12
軟體取得 10.非第一次使用 待下載啟動程式碼完成(右下角顯示100%),即會開 啟應用程式. 安裝軟體時,需使用擁有管理者(Administrator)權 限的帳戶. 注意事項: 1.此為“串流”(stream)程式碼到PC執行的方式,於 第一次使用新功能時,需下載程式碼, 請耐心等候. 2.若您的個人電腦已安裝相同應用程式, 建議先解除 該軟體的安裝. 3.若有安裝錯誤訊息出現,請跳過該訊息.
13
MATLAB 簡介 什麼是 MATLAB MATrix LABoratory 以矩陣為運算基礎的數學軟體 直譯式的數學程式語言
提供完備的數學函數,且能讓使用者定義自己的函數。 提供矩陣運算、數值分析、 統計分析、訊號處理、圖形繪製(2D/3D)……等功能
14
MATLAB Interface Workspace Current Folder Command Window
Command History Details
15
Scalar Arithmetic Operations
Symbol Operation MATLAB Form ^ exponentiation: ab a^b * multiplication: ab a*b / right division: a/b = a/b \ left division: a\b = a\b + addition: a + b a+b - subtraction: a – b a-b Example: >> (5*2+3.5)/5 ans = 2.7000
16
Order of Precedence Example: >> 5^2*2 ans = 50 >> 5*2^2 20
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) Example: >> 5^2*2 ans = 50 >> 5*2^2 20
17
矩陣的基本資料結構 直接列出矩陣內的元素產生矩陣: Example: 用逗號 (,) 或空白區隔同一列的元素
用分號 (;) 或 Enter 鍵代表一列的結束 矩陣的開始和結束,使用中括號 ([]) 表示 Example: >> A=[1 2 3] A = >> B=[1 2 3; 4 5 6] B =
18
矩陣的基本資料結構 (cont’d) 直接列出矩陣內的元素產生矩陣: Example: 或使用下列描述法構成: X=起始值:增加值:結束值
>> A=[1:2:10]
19
矩陣的基本資料結構 (cont’d) 利用 MATLAB 的敘述或函式產生: Example: >> A=ones(3,4)
>> B=linspace(1,10,4) B =
20
矩陣的索引或下標 Ref:
21
Predefined Constants Command Description ans
Temporary variable containing the most recent answer eps Specifies the accuracy of floating point precision i,j The imaginary unit Inf Infinity, ∞ NaN Indicates an undefined numerical result (Not a Number) pi The number π
22
變數命名規則與使用 Example: 第一個字母必需是英文字母。 字母間不可留空格。 字母大小寫有異
最多只能有 31 個字母,MATLAB 會忽略多餘字母(在 MATLAB 第 4 版,則是 19 個字母)。 MATLAB 在使用變數時,不需預先經過變數宣告(Variable Declaration)的程序,而且所有數值變數均以預設的 double 資料型式儲存。 Example: PSE123 (O) 3PSE21 (X) PSE_123(O) PSE-123 (X)
23
Matrix operations Symbol Operation Form Example +
Scalar-array addition A+b [6,3]+ 2 =[8, 5] - Scalar-array subtraction A-b [6,3]- 2 =[9,11] Array addition A+B [6,3]+[3,8] Array subtraction A-B [6,3]-[3,8] =[3,-5] * Matrix multiplication A*B [1,2]*[3,4]' =[11] \ Matrix left division x=A-1B A\B [1,2]\[10] =[0 5]' .* Array multiplication A.*B [3,2].*[2,4] =[6, 8] ./ Array right division A./B [4,8]./[2,4] =[2, 2] .\ Array left division A.\B [2,4].\[4,8] .^ Array exponent A.^B [3,5].^2 =[9,25] 2.^[3,5] =[8,32] [3,2].^[2,3] =[9, 8]
24
Relational operators Example: Relational Operator Meaning <
Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not equal to Example: >> x = [ 6, 3, 9]; >> y = [14, 2, 9]; >> z = (x < y) z =
25
矩陣的邏輯運算 Example: 矩陣的邏輯運算: &:And 運算(=and) |:Or 運算(=or) ~:Not 運算(=not)
any:任何一個元素不為零 all:所有元素都不為零 Example: Xor Logical exclusive-OR >> X=[ ] X = >> any(X) ans = 1 >> any(X==4) ans = 0
26
Some Useful Array Functions
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 × n matrix size(A) Returns a row vector [m n] containing the sizes of the m × 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
27
常見特殊矩陣 zeros(m,n) %維度為mxn, 元素全為0的矩陣 ones(m,n) %維度為mxn, 元素全為1的矩陣
eye(n) %維度為nxn的identity矩陣 rand(m,n) %維度為mxn,於[0,1]均勻分佈的亂數矩陣 randn(m,n) %維度為mxn,於[0,1]高斯分佈的亂數矩陣 [] 空矩陣 diag 對角矩陣 linspace 產生線性的空間向量
28
Special Characters =:指定(Assign)運算 (ex: B=A) ' : 矩陣轉置 (ex: B=A')
..:代表上一層目錄 (ex: cd ..) ...:繼續,代表指令未完,接到下一列 ,:元素分隔符號 ;:代表命令結束,且不印出執行結果 %:註解列
29
Pre-allocation 在 MATLAB 運算過程,可以隨時改變每一個矩陣的維度,以容納新的資料。但是每一次增大矩陣的容量時,MATLAB 就必須要向電腦的作業系統索取記憶體,因此會造成程式執行效率的降低,而且造成記憶體的分散使用現象(Memory Segmentation),此種由於記憶體的動態配置而造成的分散使用現象,可能導致實際雖仍有充足的記憶體,但卻未有連續空間以處理較大矩陣的現象。 基於以上種種原因,若預先知道使用矩陣的維度大小,則最好實施矩陣的預先配置(Pre-allocation),可用的指令有 zeros、ones、cell(用於配置異值陣列)及 struct(用於配置結構陣列)等。例如,欲計算矩陣 A 的 n 次方的行列式,其中 n = 1~100,可輸入如下: Example: A = [1 2 3; 4 5 6; 7 8 9]; det_value = zeros(1, 100); for i = 1:100 det_value(i) = det(A^i); end
30
工作空間與變數的儲存及載入 Workspace 中變數的保存方式: save:將 workspace 中的變數存到磁碟上
load:由磁碟上的資料檔載入變數到 workspace 中 不加任何選項(Options)時,save 指令會將工作空間內的變數以二進制(Binary)的方式儲存至副檔名為 mat 的檔案
31
工作空間與變數的儲存及載入 (cont’d)
使用 save 保存變數: save:將所有變數以二進位格式存至 “matlab.mat”中 save fname:將所有變數存至”fname.mat”中 save fname X Y:將變數 X 與 Y 存至”fname.mat”中 save fname X -ascii:使用 8 位數文字格式將變數X 存至”fname”中 save fname X -ascii -double:使用 16 位數文字格式將變數 X 存至”fname”中 save name.txt X -ascii -double –tabs :使用 16 位數文字格式將變數 X 存至”fname”.txt的文字檔中
32
工作空間與變數的儲存及載入 (cont’d)
使用 load 載入變數: load:由『matlab.mat』中載入所有變數 load fname:由『fname.mat』中載入所有變數 load fname X Y:由『fname.mat』中載入變數 X 與 Y load fname -ascii:由文字檔『fname』中載入變數 load fname.txt:由文字檔『fname.txt』中載入變數
33
Commands for Managing the Work Session
Description clc Clears the command window clear Removes all variables from memory clear var1 var2 Removes var1 and var2 from memory exist(’name’) Determine if a file or variable exists having the name ’name’ quit Stop MATLAB : Colon; generates an array having regularly spaced elements , Comma; separates elements of an array ; Semicolon; suppresses screen printing; also denotes a new row in an array . . . Ellipsis; continues a line to delay execution
34
MATLAB 下的程式寫作 MATLAB 程式的基本:M-file M-file 的特性: M-file 的種類:
Script (命令稿/命令巨集) Function (函式)
35
開啟M-File
36
MATLAB 下的程式寫作 (cont’d)
Script: 用來連續執行一連串的指令 所有執行中使用或產生的變數皆存在於 workspace,因此變數容易互相覆蓋而造成程式錯誤 沒有輸入與輸出變數 Function: 用來定義一個自訂函式 除了全域變數(global variables),所有執行中使用或產生的變數皆不存在於 workspace,因此不會和 MATLAB 基本工作空間的變數相互覆蓋 可以有輸出與輸入變數
37
MATLAB 下的程式寫作 Example: 第一列為函數定義列(Function Definition Line)
FindRoots.m function [x1 x2] = FindRoots(a,b,c) x1=(-b+(b^2-4*a*c)^0.5)/(2*a); x2=(-b-(b^2-4*a*c)^0.5)/(2*a); 第一列為函數定義列(Function Definition Line) 定義函數名稱(FindRoots,最好和檔案的檔名相同) 輸入引數( [x1 x2] ) 輸出引數(a,b,c) function為關鍵字 第二列開始為函數主體(Function Body) 描述函數運算過程,並指定輸出引數的值
38
呼叫Function [Output1, Output2, …] = CommandName(input1, input2, …) CommandName: built-in or user-defined function Example: FindRoots.m function [x1 x2] = FindRoots(a,b,c) x1=(-b+(b^2-4*a*c)^0.5)/(2*a); x2=(-b-(b^2-4*a*c)^0.5)/(2*a); >> a=1; >> b=3; >> c=1; >> [x1 x2] =FindRoots(a,b,c) x1 = x2 =
39
次函數 次函數(sub-function):一個M 檔案可以有一個以上的次函數 Example: TEST.m >> v=1;
function [x1 x2] = TEST(H) [a b c]= Cal_abc(H) [x1 x2] = FindRoots(a,b,c) >> v=1; >> [x1 x2] = TEST(v) x1 = 1.2573 x2 = Cal_abc.m function [a b c] = Cal_abc(H) a=H^3; b=H/3; c=H-3;
40
全域變數 (global variable)
此變數可在不同的函數及底稿(m-file)使用這在工程計算相當有用 Example: TEST.m global a b c a= b= c=-46.13 for i=1:11 t= *(i-1) %t in Kelvin psat(i)=antoine(t) % psat in mmHg end Antoine.m function p_vap=antoine(t) global a b c p_vap=exp(a-b/(t+c))
41
MATLAB 下的流程控制 程式的流程控制(Flow Control): 迴圈指令(Loop Command):
for …… end while …… end 條件指令(Branching Command): if … elseif … else … end switch … case … otherwise … end
42
MATLAB 下的流程控制 - for for 迴圈: 語法 1: 語法 2: for 變數=向量 運算式 end for 變數=矩陣
Example: >>x=1; >> for i=1:5 >> x=x*i; >> end >> disp(x) 120 >> x=[1 3; 2 4]; >> for i=x >> fprintf('%d\t',i) >> end
43
MATLAB 下的流程控制 - while while 迴圈: 語法: while 條件式 運算式 end % 1+ ε < 1?
Example: % 1+ ε < 1? e= 1; while (1+e) > 1 %判斷式成立 e = e/2; end e = e*2
44
MATLAB 下的流程控制 - if if 條件指令: 語法: if 條件式一 運算式一 elseif 條件式二 運算式二
運算式三 else 運算式四 end Example: if x > 10 y = log(x) elseif x >= 0 y = sqrt(x) else y = exp(x) - 1 end
45
MATLAB 下的流程控制 – switch switch 條件指令: 語法: switch 運算式 case 值一 運算式一
Example: switch 條件指令: 語法: switch 運算式 case 值一 運算式一 case 值二 運算式二 otherwise 運算式三 end for month=1:12 switch month case {3,4,5} season='Spring'; case {6,7,8} season='Summer'; case {9,10,11} season='Autumn'; otherwise season='Winter'; end fprintf('Month %d is %s.\n',month,season) Result: Month 1 is Winter. Month 2 is Winter. Month 3 is Spring. Month 4 is Spring. …..
46
MATLAB 下的流程控制 break: Terminate execution of for or while loop
return: Return to invoking function Example: for i = 1:1000 if prod(1:i) > 1e10 break;% %跳出迴圈 end disp(i) 14 det.m function d = det(A) %DET det(A) is the determinant of A. if isempty(A) d = 1; return else ... end
47
Exercise clear all A=[ ]'; B(1)=A(1);C(1)=A(1); for i=2:length(A) if A(i)>=3 B(1,i)=A(i)+C(i-1); else B(1,i)=A(i)+B(i-1); end C(1,i)=myfun(B(i)); Ans=B*C' myfun.m function C=myfun(B) while B > 2 B=B-1; end C=B^2;
48
Plotting
49
Some MATLAB Plotting Commands
Description axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of x- and y-axes. fplot(’string’, [xmin xmax]) Performs intelligent plotting of functions, where ’string’ 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 (’string’, [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(x,y) Generates a plot of the array x on rectilinear axes. legend('leg1','leg2', ...) 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(m,n,p) Splits the figure window into an array of subwindows with m rows and n columns and directs the subsequent plotting commands to the pth subwindow. text(x,y,'text') Places the string text in the figure window at point specified by coordinates x, y.
50
二維基本繪圖簡介 plot -- 繪圖指令的根本: 語法:plot(X,Y, format):將向量 Y 對向量 X 做圖
Example: >> X=[0:0.1:2*pi]; >> Y=sin(X); >> plot(X, Y, 'bx-') ‘color marker line-type')
51
Data Markers, Line Types, and Colors
Dot (.) Solid line Black k Asterisk (*) * Dashed line Blue b Cross (×) 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 Tips: Command Line:help plot
52
圖形標題與座標軸 X=[0:0.1:2*pi]; Y=sin(X); plot(X, Y, 'b--','linewidth',3)
Example: X=[0:0.1:2*pi]; Y=sin(X); plot(X, Y, 'b--','linewidth',3) title('Y vs X','fontsize',15) xlabel('X','fontsize',15) ylabel('f(X)','fontsize',15) legend('sin(X)','fontsize',15) set(gca,'fontsize',15)
53
單一圖片呈現多個圖形 使用 plot 的第三種形式,一次畫出多個數對。 使用 hold 將圖形「固定」住,重疊多個數對的繪圖結果。
使用 subplot 分割繪圖視窗,同時呈現多個子圖形。
54
單一圖片呈現多個圖形 - plot plot -- 繪圖指令的根本:
語法:plot(X1,Y1, format1, X2,Y2, format2...):將 Yi 對 Xi 以 formati 做圖 Example: >> X=[0:0.1:2*pi]; >> Y=sin(X); >> Z=cos(X); >> plot(X, Y, 'bx-', X, Z, 'r:')
55
單一圖片呈現多個圖形 - hold 使用 hold 重疊多個數對圖形: Example: >> X=[0:0.1:2*pi];
>> Y=sin(X); >> Z=cos(X); >> plot(X, Y, 'b--') >> hold on; >> xlabel('X') >> ylabel('f(X)') >> plot(X, Z, 'r:') >> text(0.2,0,'sin(X)') >> text(0.5*pi+0.2,0,'cos(X)')
56
單一圖片呈現多個圖形 - subplot 使用 subplot 分割視窗呈現數個子圖形: >> X=[0:0.1:2*pi];
Example: >> X=[0:0.1:2*pi]; >> Y=sin(X); >> Z=cos(X); >> subplot(211); >> plot(X, Y, 'b--') >> xlabel('X') >> ylabel('sin(X)') >> subplot(2,1,2); >> plot(X, Z, 'r:') >> ylabel('cos(X)')
57
Plot tools Show plot tool Hide plot tool
58
Enhance your figure Generate Code
59
三維基本繪圖簡介 – line plot t = 0:pi/50:10*pi; plot3(sin(t),cos(t),t) grid on axis square
60
三維基本繪圖簡介 – mesh plot % meshgrid:Generate X and Y arrays for 3-D plots [X,Y] = meshgrid(-3:.125:3); Z = peaks(X,Y); % mesh, meshc, meshz Mesh plots mesh(X,Y,Z); axis([ ])
61
Symbolic calculation
62
subs函數 subs(E,old,new)可以將算式 E 中 old 的部分以 new取代,其中 old 這個部分可以是符號變數或者是符號表示式,並且 new 這個部分可以是符號變數、符號表式、矩陣、數值的值,或者是數值的矩陣。 >> syms x y >> E = x^2+6*x+7; >> F = subs(E,x,y) F = y^2+6*y+7 >> F = subs(E,x,5) 62 Example:
63
solve 函數 有三種使用solve函數的方式。例如,要求解方程式 x + 5 = 0 >> eq1 = 'x+5=0';
>> solve(eq1) ans = -5 >> solve('x+5=0') ans = -5 >> syms x >> solve(x+5) ans = -5
64
limit函數 >> syms a x >> limit(sin(a*x)/x) ans = a
函數 limit(E) 可以用來求出當 x → 0的時候 E 的極限。 >> syms a x >> limit(sin(a*x)/x) ans = a 另外limit(E,v,a)這個形式可以用來求出當u → a 時的極限。舉例來說, >> syms h x >> limit((x-3)/(x^2-9),3) 1/6 >> limit((sin(x+h)-sin(x))/h,h,0) cos(x)
65
Symbolic Calculation (diff, int)
syms x f=sin(x); c=diff(f) d=diff(f,2) c_value=subs(c,2) d_value=subs(d,2) c = cos(x) d = -sin(x) c_value = d_value = syms x y f=sin(x)+cos(y); c=diff(f,x) c2=diff(f,x,2) d=diff(f,y) d2=diff(f,y,2) c = cos(x) c2 = -sin(x) d = -sin(y) d2 = -cos(y) syms x f=-2*x/(1+x^2)^2; c=int(f) d=int(f,0,1) c = 1/(1+x^2) d = -1/2
66
拉氏轉換 Example: >> syms b t >> laplace(t^3) ans = 6/s^4
>> laplace(exp(-b*t)) 1/(s+b) >> laplace(sin(b*t)) b/(s^2+b^2)
67
反拉氏轉換 Example: >> syms b s >> ilaplace(1/s^4) ans = t^3/6
>> ilaplace(1/(s+b)) exp(-b*t) >> ilaplace(b/(s^2+b^2)) sin(b*t)
68
特徵方程式以及特徵根 Example: >> syms k >> A = [0 ,1;-k, -2];
>> poly(A) ans = x^2+2*x+k >> solve(ans) [ -1+(1-k)^(1/2) ] [ -1-(1-k)^(1/2) ]
69
Curve fitting (regression)
70
Functions for Polynomial Regression
Command Description p = polyfit(x,y,n) 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. [p,s, mu] = polyfit(x,y,n) 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. Example: The linear function y = mx + b gives a straight line when plotted on rectilinear axes. Its slope is m and its intercept is b. → p = polyfit(x, y, 1)
71
Curve Fitting Tools Choose model Create data set
72
Curve Fitting Tools (cont’d)
73
Solving ODE by m-file
74
用 MATLAB 解 ODE 解 ode 可用的 function:ode23(), ode113(), ode15s(), ode23s(), ode23t(), ode23tb(), ode45() 基本語法(以 ode45() 為例): [T,Y] = ode45('F',TSPAN,Y0,OPTIONS) or [T,Y] = T:時間 F:ode function M-file 定義檔檔名 TSPAN:積分時間 Y0:初始值 OPTIONS:特殊選項 P1, P2 …:其餘欲傳給 ode function M-file 的參數
75
Example 1 rigid.m function dy = rigid(t,y)
dy = zeros(3,1); % a column vector dy(1) = y(2) * y(3); dy(2) = -y(1) * y(3); dy(3) = * y(1) * y(2);
76
Example 1 (cont’d) >> [T,Y] = 12],[0 1 1]); >> plot(T,Y(:,1),'-',T,Y(:,2),'-.',T,Y(:,3),'.')
77
Example 2 先將二階化成標準格式,令 vdp1.m 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 [0 25], [3 3]);
78
Example 3 – VDV reaction vdv.ode.m function xdot = vdv_ode(t,x)
ca=x(1); cb=x(2); k1=5/6; k2=5/3; k3=1/6; fov=4/7; caf=10; dcadt=fov*(caf-ca)-k1*ca-k3*(ca^2); dcbdt=-fov*cb+k1*ca-k2*cb; xdot=[dcadt;dcbdt];
79
Example 3 (cont’d) x0=[2;1.117]; tspan=[0 5];
subplot(2,1,1) plot(t,x(:,1)) xlabel('t') ylabel('ca') subplot(2,1,2) plot(t,x(:,2)) ylabel('cb')
80
Summary of coding Writing down before coding Looking for help
Using recognizable name of variable Checking matrix dimension Checking loop and iteration
81
Backup materials
82
Numerical differentiation
True Slope
83
Numerical Differentiation(diff)
d = diff(x) = [x(2) − x(1), x(3) − x(2), , x(n) − x(n − 1)] Example: x=0:0.1:1; y=[ ]; dx=diff(x); dy=diff(y); dydx=diff(y)./diff(x) dydx =
84
Numerical Differentiation Functions
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(p2,p1) 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. [n,d]=polyder(p2,p1) Returns the vectors n and d containing the coefficients of the numerator and denominator polynomials of the derivative of the quotient p2/p1, where p2 and p1 are polynomials.
85
Numerical Differentiation Polynomial Derivatives
p1 = [5,2]; p2 = [10,4,-3]; der2 = polyder(p2) prod = polyder(p2,p1) [num,den] = polyder(p2,p1) der2 = 20 4 prod = num = den =
86
Numerical integration
87
Numerical Integration
Command Description trapz(x,y) 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(’function’,a,b,tol) Uses an adaptive Simpson’s rule to compute the integral of the function ’function’ 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(’function’,a,b,tol) Uses Lobatto quadrature to compute the integral of the function ’function’. The rest of the syntax is identical to quad.
88
Numerical Integration
x = linspace(0, pi, 10); ans = y = sin(x); trapz(x, y) x = linspace(0, pi, 100); ans = y = sin(x); x = linspace(0, pi, 1000); ans = y = sin(x);
89
Interpolation
90
Polynomial Interpolation Functions(1D)
y_est=interp1(x,y,x_est,'method') This command specifies alternate methods. The default is linear interpolation. Available methods are: nearest - nearest neighbor interpolation linear - linear interpolation spline - piecewise cubic spline interpolation (SPLINE) pchip - piecewise cubic Hermite interpolation (PCHIP) cubic - same as ’pchip’
91
Polynomial Interpolation Functions(2D)
z_est=interp2(x,y,z,x_est,y_est,’method’) This command specifies alternate methods. The default is linear interpolation. Available methods are: nearest - nearest neighbor interpolation linear - bilinear interpolation (or bilinear) spline - cubic spline interpolation (SPLINE) cubic - bicubic interpolation
92
Minimization (optimization)
93
Minimizing A Function of Variables (fminsearch)
minimum of , near (0,0) function f = f146(x) f = x(1).*exp(-x(1).^2-x(2).^2); %% end, stored in f145.m fminsearch('f146',[0,0]) % [f, fval] = fminsearch(’f146’,[0,0]) ans =
94
Other Built-in Functions
fmincon: find minimum of constrained nonlinear multivariable function fminbnd: find minimum of single-variable function on fixed interva Isqlin: constrained linear least-squares problems Equation lsqnonlin: Solve nonlinear least-squares (nonlinear data-fitting) problems quadprog: Solve quadratic programming problems
95
Optimization Tool
96
Solving algebraic equation
97
Finding Roots of Equations
Equation Type solver Polynomial roots roots continuous function of one variable fzero nonlinear equations fsolve (fminsearch…)
98
roots roots: polynomial roots syntax: x = roots([c1 c2 c3…. cn+1])
Example: p = [ ] r = roots(p) r =
99
Some Polynomial Functions
Command Description poly(r) Computes the coefficients of the polynomial whose roots are specified by the array r. The resulting coefficients are arranged in descending order of powers. polyval(a,x) Evaluates a polynomial at specified values of its independent variable x. The polynomial’s coefficients of descending powers are stored in the array a. The result is the same size as x. roots(a) Computes an array containing the roots of a polynomial specified by the coefficient array a.
100
Polynomial Roots x3 - 7x2 + 40x -34 =0 a = [1, -7, 40, -34],... roots(a) a = ans = i i 1.000 roots = 1, 3 ± 5i r = [1, 3+5i, 3-5i],... poly(r) r = i i ans =
101
fzero 函數 fzero: find root of continuous function of one variable
syntax: x = x0) x:解 FUN:定義問題的 function M-file 檔名 x0:初始猜值矩陣
102
Example - fzero >> fzero('func01',[3 6]) ans = 3.9270
func01.m function f=func01(x) f = sin(x) - cos(x); >> fzero('func01',[3 6]) ans = 3.9270 >> fzero('func01',[0 3]) ans = 0.7854
103
fsolve 函數 fsolve: 解聯立方程式 語法: x = fsolve(@FUN, x0) x:解
FUN:定義問題的 function M-file 檔名 x0:初始猜值矩陣 Reamark:fsolve() 是 optimization toolbox 的指令
104
Example - fsolve A=[1 7 5; 2 3 4;9 6 8]; b=[ 2 ;4;6]; c=inv(A)*b
Method 1 Method 2 function F=func01(X) A=[1 7 5; 2 3 4;9 6 8]; b=[ 2 ;4;6]; F=A*X-b A=[1 7 5; 2 3 4;9 6 8]; b=[ 2 ;4;6]; c=inv(A)*b x= 2.0308 x0=[1 1 1] x=fsolve('func01',x0) x= 2.0308 % Use help fsolve for details
105
Example Van de Vusse reaction in an isothermal CSTR:
106
Example vdv_sol_ad.m x0=[2;1.117]; k1=5/6; k2=5/3; k3=1/6; fov=4/7;
caf=10; options=optimset('Display','iter'); cas=x(1) cbs=x(2) vdv_ad.m function F = vdv_ae(x,k1,k2,k3,fov,caf) F = [fov*(caf-x(1))-k1*x(1)-k3*(x(1)^2); -fov*x(2)+k1*x(1)-k2*x(2)];
107
Simulink
108
Simulink 簡介 什麼是 Simulink ? MATLAB 提供的一個 toolbox 應用於動態系統模擬
提供 GUI,使動態系統的建立如同畫方塊圖(Block Diagram)
109
啟動 Simulink 啟動 Simulink: 直接在 command window 鍵入 「simulink」
110
啟動 Simulink Simulink 的外觀:
111
動態模型的建立 動態模型的建立步驟: 開啟一個空白的模型(Model)
開啟適當的 Library 視窗,找出所有需要的 Block,將該 Block 拖入或複製至空白模型視窗 用滑鼠雙擊各 Block 開啟對話視窗,適當設定各 Block 所需的參數 利用滑鼠連接各個 Block,建立完整的動態系統
112
動態模型的建立
113
Solving ODE using dee
114
dee 啟動指令 A window named dee will appear Command Line: dee
115
模型建立
116
執行指令與作圖 k1=5/6; k2=5/3; k3=1/6; fov=4/7; caf=10; x0=[2;1.117];
sim('vdv_sim_4',[0 5]) subplot(2,1,1) plot(t,ca) xlabel('t') ylabel('ca') subplot(2,1,2) plot(t,cb) ylabel('cb')
117
Debug
118
Debug mode breakpoint Run vdv_sol_ae.m
119
Debug mode (cont’d) Step Continue
120
Solving ODE using S-function
121
Example – VDV reaction Enter search term Constant S-function
122
Command Line: open sfuntmpl.m sfuntmpl.m will appear
123
vdv_sfun.m function [sys,x0,str,ts] = vdv_sfun(t,x,u,flag,x0) switch flag, case 0, [sys,x0,str,ts]=mdlInitializeSizes(x0); case 1, sys=mdlDerivatives(t,x,u); case 2, sys=mdlUpdate(t,x,u); case 3, sys=mdlOutputs(t,x,u); case 4, sys=mdlGetTimeOfNextVarHit(t,x,u); case 9, sys=mdlTerminate(t,x,u); otherwise DAStudio.error('Simulink:blocks:unhandledFlag', num2str(flag)); end
124
vdv_sfun.m (cont’d) function [sys,x0,str,ts]=mdlInitializeSizes(x0) sizes = simsizes; sizes.NumContStates = 2; sizes.NumDiscStates = 0; sizes.NumOutputs = 2; sizes.NumInputs = 2; sizes.DirFeedthrough = 0; sizes.NumSampleTimes = 1; % at least one sample time is needed sys = simsizes(sizes); str = []; ts = [0 0];
125
vdv_sfun.m (cont’d) function sys=mdlDerivatives(t,x,u) ca=x(1); cb=x(2); fov=u(1); caf=u(2); k1=5/6; k2=5/3; k3=1/6; dcadt=fov*(caf-ca)-k1*ca-k3*(ca^2); dcbdt=-fov*cb+k1*ca-k2*cb; sys = [dcadt;dcbdt]; function sys=mdlUpdate(t,x,u) sys = [];
126
vdv_sfun.m (cont’d) function sys=mdlOutputs(t,x,u) sys = [x(1);x(2)]; function sys=mdlGetTimeOfNextVarHit(t,x,u) sys = []; function sys=mdlTerminate(t,x,u)
127
Example – VDV reaction (cont’d)
1 2 4 3
128
Example – VDV reaction (cont’d)
Command Line: x0=[2;1.117]
129
Example – VDV reaction (cont’d)
sfun_plot.m subplot(2,1,1) plot(t,ca) xlabel('t') ylabel('ca') subplot(2,1,2) plot(t,cb) ylabel('cb')
130
MV step change Step
131
Command Line: x0=[3;1.117] Start Simulation
Reach New Steady State
132
Refine Simulink file
133
Refine Simulink file (cont’d)
Create Subsystem in mouse right click menu
134
Refine Simulink file (cont’d)
Mask Subsystem in mouse right click menu
135
Refine Simulink file (cont’d)
Add
136
Refine Simulink file (cont’d)
Right double click on subsystem will appear the following window:
137
Simulating LTI model
138
LTI model 的建立 [ys,ts]=step(vdv_tf); plot(ts,ys)
[yi,ti]=impulse(vdv_tf); plot(ti,yi) pole(vdv_tf) tzero(vdv_tf) A=[ ; ]; B=[7;-1.117]; C=[0 1]; D=[0]; vdv_ss=ss(A,B,C,D) num=[ ]; den=[ ]; vdv_tf=tf(num,den) vdv_zpk=zpk(2.817,[ ],-1.117) vdv_tf1=tf(vdv_ss) vdv_zpk1=zpk(vdv_tf1) vdv_tfd=c2d(vdv_tf,1,'zoh') vdv_tf2=tf(num,den,'Inputdelay',1)
139
LTI model 進階分析 kc=1; figure(1) bode(kc*vdv_tf) figure(2)
[mag,phase,w]=bode(kc*vdv_tf) subplot(2,1,1),loglog(w,squeeze(mag)) subplot(2,1,2),semilogx(w,squeeze(phase)) [Gm,Pm,Wg,Wp]=margin(mag,phase,w) nyquist(kc*vdv_tf)
140
Simulate LTI model using Simulink
141
LTI model 的建立 Transfer Fcn
142
Closed-loop simulation
143
PID Controller
144
Look Under Mask
145
Solving PDE
146
Numerical Methods for PDE(pdepe)
pdepe solves PDEs of the form with boundary conditions
147
Numerical Methods for PDE(pdepe)
function [c,b,s] = eqn1(x,t,u,DuDx) %EQN1: MATLAB function M-le that %species %a PDE in time and one space %dimension. c = 1; b = DuDx; s = 0; function [pl,ql,pr,qr] = bc1(xl,ul,xr,ur,t) %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; function value = initial1(x) %INITIAL1: MATLAB function M-le %that species the initial condition %for a PDE in time and one space %dimension. value = 2*x/(1+x^2);
148
Numerical Methods for PDE(pdepe)
%PDE1: MATLAB script M-le that solves and plots %solutions to the PDE stored in eqn1.m m = 0; x = linspace(0,1,20); t = linspace(0,2,10); %Solve the PDE u = %Plot solution surf(x,t,u); title('Surface plot of solution.'); xlabel('Distance x'); ylabel('Time t');
Similar presentations