2016-05-17 28 views
2

是否有辦法使條件成立,如果在if下的語句/矩陣中出現錯誤,則執行else下的語句?當'if'部分下的語句出現錯誤時,如何將控件移動到「if-else」的else部分?

即,

if (some condition) 
some statment1/matrix1/variable1 
some statement2/matrix2/variable2 
some statement3/matrix3/variable3 

else newstatement/matrix %come to else part of the code if any of the statements 1,2 or 3 under if condition yields any error like dimension mismatch or anyother 
end 

回答

6

沒有內置的機制跳轉到else部分。但你可以使用這樣的結構:

condition_flag = (some condition); 
error_flag = false; 

if condition_flag 
    try 
     some statment1/matrix1/variable1 
     some statement2/matrix2/variable2 
     some statement3/matrix3/variable3 
    catch 
     error_flag = true; 
    end 
end 

if ~condition_flag || error_flag 
    %if any of the statements 1,2 or 3 under if condition yields any error like dimension mismatch or anyother 
    .... 
    error_flag = false; 
end 
0

Mohsen Nostrania之一的替代解決方案。

else_flag=true; 
if (condition) 
    try 
    %% The if code 
    else_flag=false; 
    end 
end 
if else_flag 
    %% The else code 
end 

else_flag=false;的命令被執行,只有當condition爲真並且<if code>內發生任何錯誤。

請注意,這兩種解決方案都是按照您的要求進行的 - 將執行<if code>命令,直至發生錯誤,然後執行<else code>

+0

你try-catch塊缺少catch語句 – Matt

+0

@馬特我知道。如果你不關心錯誤細節,你可以禁止警告'丟失catch語句並忽略它。如果catch序列被執行,其他代碼將被執行。 – Crowley

0

如果一個人想降低if聲明TRE號:

try 
    if statement 
    %% The if code 
    else 
    %% Obvious error 
    a(0); 
    end 
catch 
    %% The else code 
end