File Exchange

image thumbnail


version (1.1 KB) by Gerald Dalley
Assert function that expands like the C macro assert

1 Download

Updated 07 Nov 2006

No License

% Evaluates the test condition in the caller's context. If the result is
% false, an error is thrown indicating that the test failed.
% TESTCONDITION should be a string.
% If TRUTHVALUE is zero, an error is thrown. The text of the error
% contains ERRMSG if supplied. This version of ASSERT was made to
% promote compatibility with Kevin Murphy's Bayes Net Toolbox (i.e. he
% uses this syntax). TRUTHVALUE must be a logical or a number.
% assert('1==2') ==> assertion error generated
% assert(1==2) ==> assertion error generated (BNT syntax)
% assert 1==2; ==> assertion error generated
% x=1; assert('x==1') ==> no error
% x=1; assert x==1; ==> no error
% assert('{a==3') ==> error generated by Matlab (bad assert code)

Cite As

Gerald Dalley (2021). assert.m (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (4)

Ben FrantzDale

Just what I need for backward compatibility.

As for Duane's question: Assert in C/C++ is also wrapped in #ifdefs so it isn't used in production, only in debugging. This is good for range checking, for example. It is immensely useful for writing correct code by helping you track down bugs right as they happen. Because it is used so frequently, a function is justified. Otherwise you wind up with code full of if ~condition, error, end.

Naveen Mishra

Finally there is a builtin assert function in MATLAB R2007a.

Roger Krill

Duane Hanselman needs to expand his mind.

In the code, I noticed an inconsistency in the error messages. Please fix this.

Also, is there a way to show the testCondition condition/string itself as part of the error message?

Duane Hanselman

I am not familiar with C so this function seems like a lot of effort when none is needed. Why not use
if ~(place some boolean test here)
error('ASSERT FAILED: name the test failed here')
Why not do MATLAB in MATLAB? Why post copyrighted code? If I modify your code to what I have above, I am required by you to include your copyright notice and permission. Why?

MATLAB Release Compatibility
Created with R14SP2
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired: Assertion function

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!