作為一種程式語言,matlab同一般高階程式語言一樣,為使用者提供了豐富的程式結構語言來實現使用者對程式流程的控制。matlab的程式路程控制主要包括迴圈控制和條件選擇控制。
for迴圈結構的格式為:
for 迴圈變數 = 向量表示式
迴圈體語句
end
該迴圈結構的執行方式為:從向量表示式的第一列開始,依次將向量表示式各列的值賦值給迴圈變數,然後執行迴圈體語句組中的命令,直到最後一列。通常使用的for迴圈格式為:
for i=s: h:e
求1-50的累加和。
>> sum = 0;
>> for i = 1 : 1:50
sum = sum + i;
end>> sum
sum =
1275
for迴圈語句可以實現多重迴圈,但for與end必須成對出現。
while迴圈結構的基本格式為:
while 關係表示式
迴圈體語句組
end
該迴圈結構的執行方式為:
(1)判斷關係表示式是否為真,若為真,則執行(2),否則執行(3);
(2)執行迴圈體語句組中的命令,再返回至(1);
(3)執行end語句,即迴圈結束。
>> sum = 0;
>> i = 1;
>> while i<= 50
sum = sum + i;
i = i + 1;
end>> sum
sum =
1275
if 條件表示式1
條件塊語句組1
elseif 條件表達2
條件塊語句組2
...elseif 條件表示式n-1
條件塊語句n-1
else
條件塊語句組n-1
end
學生成績分類:90分以上為a,80~89分為b,70~79分為c,60~69分為d,60分以下為e,要求輸入乙個分數輸出其對應等級。
>> grade = input("enter a grade:");
if grade >=90
degree = 'a';
elseif (grade >= 80) && (grade < 90)
degree = 'b';
elseif (grade >= 70) && (grade < 80)
degree = 'c';
elseif (grade >= 60) && (grade < 70)
degree = 'd';
else
degree = 'e';
endenter a grade:90
>> disp(['the degree is:',degree])
the degree is:a
switch條件選擇結構用於多分支選擇,其基本格式為:
switch 表示式
case 常量表示式1
語句組1;
case 常量表示式2
語句組2;
....
case 常量表示式n
語句組n;
otherwise
語句組n+1
end
matlab中,switch條件選擇結構只執行第乙個匹配的case對應的語句組,故不需要break。
>> degree = input("enter a degree:");switch (degree)
case 'a'
disp('the grade is 90-100.');
case 'b'
disp('the grade is 80 -90.');
otherwise
disp('the grade is under 80.');
endenter a degree:'c'
the grade is under 80.
MATLAB程式流程控制
1.條件結構 輸入乙個百分制成績,輸出成績等級a b c d e。其中90 100分為a,80 89分為b,70 79分為c,60 69分為d,60分以下為e。e.g.if語句 a input 分數 if a 100 disp 出錯!elseif a 90 disp a elseif a 80 di...
Matlab程式流程控制
幾個概念 1.指令碼檔案為看可以在命令還直接執行的檔案,也稱為命令檔案 2.函式檔案為定義的乙個函式,需要進行呼叫才能夠使用,不能夠直接執行 順序結構 a input 提示資訊 選項 如 a input a disp 輸出項 強行終止ctrl c 選擇結構 if 條件 語句組end 注意條件只有非0...
MATLAB基礎學習 流程控制
單分支if語句 當條件為標量時,非零表示條件成立,為零時表示條件不成立。當條件結果為矩陣時,如果矩陣不包含零元素或為空,則表示條件成立,否則條件不成立。a 1 2 3 b 0 1 2 3 if a disp a條件成立!endif b disp b條件成立!雙分支if語句 語法 if 條件 語句塊 ...