MATLAB 結構化財務程式之撰寫 MATLAB財務程式實作應用研習 主題五 資管所 陳竑廷 Give a simple test on the code in P9 (switch case) In p. 13, can you explain how to avoid dynamic memory allocation? P18: Line 1: for n=1:5 -->Lack one parameter Can you give more precise explainations on meshgrid? 資管所 陳竑廷
大綱 非循序指令 決策、選擇 迴圈、反覆 巢狀結構與內縮 向量化
一、非循序指令 循序 (Sequencing) 根據code由上而下循序逐行執行每一個指令 非循序 選擇 反覆
Selection if 提款金額確認 switch 功能選擇 ATM提款 提款金額 < 存款:允許 > :否決
if if 邏輯條件一 運算指令一 elseif 邏輯條件二 運算指令二 elseif 邏輯條件三 運算指令三 else 運算指令N end ˙ else 運算指令N end S=55 %標的物價格 X=60 %履約價格 if S<X disp(‘價內賣權’) elseif S==X disp(‘價平賣權’) else disp(‘價外賣權’) end 最常用的條件指令是 if - then - else,其使用語法為: if 條件式 運算式一; else 運算式二; end 當條件式成立時,MATLAB 將執行運算式一,否則,就執行運算式二。若不需使用運算式二,則可直接省略 else 和運算式二。
if S=55 %標的物價格 X=60 %履約價格 if S<X disp(‘價內賣權’) elseif S<60 disp(‘S<60’) elseif S==X disp(‘價平賣權’) else disp(‘價外賣權’) end
error函數 語法 error(message) 當遇到此函數時,MATLAB會以紅色字體顯示message,此時M檔將停止執行,MATLAB回到命令視窗
error函數 S=input(‘請輸入標的物價格’); if S<0, error(‘價格須為正值’),end
switch otherwise switch 評估描述子(整數或字串) case 數值(或字串)條件一 運算指令一 運算指令二 ˙ otherwise 運算指令N end switch color case(‘red’) signal=‘景氣過熱’ case(‘green’) signal=‘景氣穩定’ case(‘blue’) signal=‘景氣略冷’ otherwise signal=‘景氣衰退’ end switch expression case value(1) statement(1) case value(2) statement(2) case value(n-1) statement(n-1) otherwise statement(n) end 在上述語法中,expression 為一數值或字串,當其值和 value(k) 相等時,MATLAB 即執行 statement(k) 並跳出 switch 指令。若 expression 不等於 value(k),k=1, 2, …, n-1,則 MATLAB 會執行 statement(n) 並跳出 switch 指令。 Give a simple test on the code in P9 (switch case)
switch switch color case(‘red’) signal=‘景氣過熱’ case(‘green’) case(‘blue’) signal=‘景氣略冷’ otherwise signal=‘景氣衰退’ end
Repetition for while 進行指定次數的重複動作之後停止。 次數已定義 在某邏輯條件不成立時,才停止執行重複動作。 次數未定義
for for dt = 2 : 1 : 8 disp(‘★’) end for index = start : increment : end statements end for dt = 2 : 1 : 8 disp(‘★’) end for 迴圈的使用語法如下: for 變數 = 向量, 運算式 end 其中變數的值會被依次設定為向量的每一個元素值,來執行介於 for和 end 之間的運算式。 另一種 for 迴圈的使用語法如下:for 變數 = 矩陣, 此時變數的值會被依次設定為矩陣的每一個直行,來執行介於 for 和 end 之間的運算式。 2345678
for 倒數 for dt = 4 : -1 : 2 disp(‘★’) end for index = start : increment : end statements end for dt = 4 : -1 : 2 disp(‘★’) end 432
Preallocation Matlab stores matrices in contiguous blocks of memory. When the size of a matrix changes, Matlab, if it has not preallocated enough space, must find a new chunk of memory large enough and copy the matrix over. When a matrix grows inside of a loop, this process may have to be repeated over and over again causing huge delays. It can therefore significantly speed up your code by preallocating a chunk of memory before entering into a loop. 當使用者每增加一個新陣列元素時, MATLAB會自動增加其陣列的容量大小。但是,非常耗時。 因此,在進入迴圈之前,若能預先分配適當的記憶體,則其陣列的容量大小只需被指派一次,可提昇記憶體的使用效能。
Preallocation tic for i = 1:30000 A(i) = i; end without = toc tic B = zeros(30000,1); % Preallocate B with the zeros command. for i = 1:30000 B(i) = i; end with = toc ratio = without / with tic 就是把 Matlab 內建的碼表歸零、開始計時; toc 就是把碼表停止,並輸出計時的結果。 Zeros 用來製造全是零的方陣、向量、序列
while while其邏輯條件判定為 false 時,程式才會跳出迴圈。 while condition statements end while pwd != password pwd = input(‘密碼:’); end while condition statements end while 迴圈使用語法如下: while 條件式 運算式; end
while…break while…break可使程式在某一個邏輯條件為 true 的情況下從迴圈跳出。 white condition(1) statements(A) if condition(2), break , end statements(B) end 實例
while…break S %目前股價 min_p = 20 %停損點 Max_p = 40 %停利點 while S < Max_p if S < min_p , break , end Keep_Stock(…) end Sell_Stock(…)
二、巢狀結構與內縮 Nesting and Indentation for … end 巢狀結構: 程式中的結構可以『築巢』於程式中另外的結構之中 巢狀結構: for … end
二、巢狀結構與內縮 for i = 1 : 1 : 2 for j = 1 : 1 : 9 disp(i*j) end 實例 >> m=1:5; >> [nn,mm]=meshgrid(n,m); >> A=nn.^2+mm.^2
三、Vectorization Matlab is an interpreted language, which means that each line of code must be reduced to machine instructions as the program runs, whereas with compiled code, this is done before execution. But where Matlab is at a disadvantage, is with regard to loops. Although recent versions have seen a considerable increase in speed, loops are still a major bottleneck. We can frequently replace loops with matrix operations or calls to fast, built in functions - a process called vectorization. Matlab is an interpreted language, which means that each line of code must be reduced to machine instructions as the program runs, whereas with compiled code, this is done before execution. Moreover, compiled code can often be optimized automatically by the compiler in ways interpreted code cannot. As such, interpreted code is generally slower than an equivalent compiled version. Many of Matlab's built in functions, however, particularly those involving matrix operations, are highly optimized and compiled in a low level language like C or Fortran resulting in very fast code. But where Matlab is at a disadvantage, is with regard to loops. Although recent versions have seen a considerable increase in speed, loops are still a major bottleneck. Thankfully, we can frequently replace loops with matrix operations or calls to fast, built in functions - a process called vectorization. Learning how to do this well is an extremely important skill. the speed increase, and the relative terseness of the vectorized versions.
Non-vectorized Vectorized A = rand(200,200); tic Bnv = zeros(size(A)); for i=1:size(A,1) for j=1:size(A,2); Bnv(i,j) = log(A(i,j)); end nonvec = toc Vectorized A = rand(200,200); tic Bv = log(A); vec = toc; MATLAB具有強大陣列運算能力,因此MATLAB向量化的運算方式可提供更有效率的迴圈運算方式。 只要有相當的陣列解法可用來解決問題,就應該避免使用 for 迴圈。 常用的底是 e 、 10 和 2。 以 e 為底的對數稱為自然對數,以 10 為底的對數稱為常用對數。 Matlab 分別提供三個函式 log( ) 、 log10( ) 和 log2( ) 對應上述三種底
Non-vectorized version
附錄 tic toc Zeros rand( ) log( ) 、 log10( ) 、 log2( ) 把 Matlab 內建的碼表歸零、開始計時 toc 把碼表停止,並輸出計時的結果 Zeros 用來製造全是零的方陣、向量、序列 rand( ) 函式會呼叫其內建的亂數產生器來製造亂數矩陣 log( ) 、 log10( ) 、 log2( ) 對數。底分別為 e 、 10 、 2。
Thank you.