[转]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  

  

原文地址:https://www.cnblogs.com/rong86/p/3552483.html