1、MATLAB財務程式實作應用研習 主題五資管所 陳竑廷2大綱 非循序指令 決策、選擇 迴圈、反覆 巢狀結構與內縮 向量化3一、非循序指令循序(Sequencing)根據code由上而下循序逐行執行每一個指令非循序選擇反覆4Selection if提款金額確認 switch功能選擇5ifif 邏輯條件一運算指令一elseif 邏輯條件二運算指令二elseif 邏輯條件三運算指令三else運算指令endS=55 標的物價格X=60 履約價格if SXdisp(價內賣權)elseif S=Xdisp(價平賣權)elsedisp(價外賣權)end6ifS=55標的物價格X=60 履約價格if SXdi
2、sp(價內賣權)elseif S60disp(S60)elseif S=Xdisp(價平賣權)elsedisp(價外賣權)end7error函數語法 error(message)當遇到此函數時,MATLAB會以紅色字體顯示message,此時M檔將停止執行,MATLAB回到命令視窗8error函數S=input(請輸入標的物價格);if S0,error(價格須為正值),end9switchswitch 評估描述子(整數或字串)case 數值(或字串)條件一運算指令一case 數值(或字串)條件二運算指令二otherwise運算指令endswitch colorcase(red)signal=
3、景氣過熱case(green)signal=景氣穩定case(blue)signal=景氣略冷otherwisesignal=景氣衰退end10switch colorcase(red)signal=景氣過熱case(green)signal=景氣穩定case(blue)signal=景氣略冷otherwisesignal=景氣衰退endswitch11Repetition for 進行指定次數的重複動作之後停止。次數已定義 while 在某邏輯條件不成立時,才停止執行重複動作。次數未定義12forfor index=start:increment:endstatementsendfor dt
4、=2:1:8disp()end13for 倒數for index=start:increment:endstatementsendfor dt=4:-1:2disp()end14Preallocation 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 matr
5、ix 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.15Preallocationticfor i=1:30000 A(i)=i;endwithout=tocticB=zeros(3
6、0000,1);%Preallocate B with the zeros command.for i=1:30000 B(i)=i;endwith=tocratio=without/with16whilewhile conditionstatementsendwhile pwd!=password pwd=input(密碼:);end while其邏輯條件判定為 false 時,程式才會跳出迴圈。17whilebreak whilebreak可使程式在某一個邏輯條件為 true 的情況下從迴圈跳出。white condition(1)statements(A)if condition(2),
7、break,endstatements(B)end18whilebreakS%目前股價min_p=20%停損點Max_p=40%停利點while S Max_pif S min_p,break,endKeep_Stock()endSell_Stock()19二、巢狀結構與內縮Nesting and Indentation程式中的結構可以築巢於程式中另外的結構之中巢狀結構:forforendend20二、巢狀結構與內縮for i=1:1:2for j=1:1:9 disp(i*j)endend21三、VectorizationMatlab is an interpreted language,w
8、hich 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 m
9、ajor bottleneck.We can frequently replace loops with matrix operations or calls to fast,built in functions-a process called vectorization.22Non-vectorizedA=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);endendnonvec=tocVectorizedA=rand(200,200);tic Bv=log(A);vec=toc;23Non-vectorized versionVectorized version24 附錄 tic 把 Matlab 內建的碼表歸零、開始計時 toc 把碼表停止,並輸出計時的結果 Zeros 用來製造全是零的方陣、向量、序列 rand()函式會呼叫其內建的亂數產生器來製造亂數矩陣 log()、log10()、log2()對數。底分別為 e、10、2。