一條if語(yǔ)句后可以跟一個(gè)(或多個(gè))可選elseif...和一條else語(yǔ)句,這對(duì)于測(cè)試各種條件非常有用。
當(dāng)使用if ... elseif ... else語(yǔ)句時(shí),要牢記以下幾點(diǎn):
一個(gè)if可以有零個(gè)或另一個(gè),并且必須在其他elseif之后。
一個(gè)if可以具有零個(gè)或多個(gè)elseif,并且它們必須位于else之前。
如果else if成功,則不會(huì)測(cè)試其余的elseif。
if <expression 1> %當(dāng)表達(dá)式1為true時(shí)執(zhí)行 <statement(s)> elseif <expression 2> %當(dāng)布爾表達(dá)式2為true時(shí)執(zhí)行 <statement(s)> Elseif <expression 3> %當(dāng)布爾表達(dá)式3為true時(shí)執(zhí)行 <statement(s)> else %當(dāng)上述條件都不為true時(shí)執(zhí)行 <statement(s)> end
創(chuàng)建一個(gè)腳本文件并在其中鍵入以下代碼-
a = 100; %檢查布爾條件 if a == 10 %如果condition為真,則打印以下內(nèi)容 fprintf('Value of a is 10\n' ); elseif( a == 20 ) % 如果條件成立的話 fprintf('Value of a is 20\n' ); elseif a == 30 % 如果條件成立的話 fprintf('Value of a is 30\n' ); else %如果沒有一個(gè)條件是真的 fprintf('None of the values are matching\n'); fprintf('Exact value of a is: %d\n', a ); end編譯并執(zhí)行上述代碼后,將產(chǎn)生以下結(jié)果-
None of the values are matching Exact value of a is: 100