[轉]matlab語言中的assert斷言函數


MATLAB語言沒有系統的斷言函數,但有錯誤報告函數 error 和 warning。由於要求對參數的保護,需要對輸入參數或處理過程中的一些狀態進行判斷,判斷程序能否/是否需要繼續執行。在matlab中經常使用到這樣的代碼:

if c<0  
    error(['c = ' num2str(c) '<0, error!']);  
end  

  使用assert斷言函數就可以寫成:

assert(c>=0, ['c = ' num2str(c) '<0 is impossible!']);  

  還可以直接寫成:

assert(c>=0)

斷言函數assert:在程序中確保某些條件成立,否則調用系統error函數終止運行。

1、使用示例:

  

 assert(1==1)  
 assert(1+1==2, '1+1~=2')  
 assert(x>=low_bounce && x<=up_bounce, 'x is not in [low_bounce,   
 up_bounce]');  

2、輸入參數說明 

c ——斷言判斷條件

msg_str——斷言失敗時顯示提示內容

function assert(c,msg_str)

 

if c, return; end  % 斷言成立,直接返回  
if nargin>1  
    error(['assert failure: ', msg_str]);  
else  
    error('assert failure: Assertion does not hold!');  
end  
end  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM