Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you turn off assertions in MATLAB?

Tags:

assert

matlab

After debugging my MATLAB code, I'd like to be able to turn off assertions to get a bit of extra speed if possible. (The expression inside the assertion is very short and quick, but there are a lot of calls inside tight loops, so it adds up. Yes, I profiled.) How do I do that globally in MATLAB? I'm looking for something akin to defining NDEBUG in C/C++, or enabling optimization in Python, or -disableassertions flag in Java. Find/replace of assert( with %assert( is too ugly for my taste.

like image 220
Nicu Stiurca Avatar asked Oct 10 '13 23:10

Nicu Stiurca


1 Answers

It occurred to me after posting these solutions that while effectively disabling assertions, they don't prevent execution of the expression. Perhaps you could exploit short-circuiting of logical expressions (true || expr) to avoid evaluating expr. This could be done by using a global NDEBUG in place of that true. That is, use assert(NDEBUG || expr) so that expr won't be evaluated when NDEBUG is true. For example,

% parentCode.m (or typed on command prompt)
global NDEBUG; NDEBUG=true;
testassertions % test script below

% testassertions.m
global NDEBUG
if isempty(NDEBUG), NDEBUG=false; end
assert(NDEBUG || fprintf('NO\n')==2) % did fprintf write 3 characters? (no, 4)
disp('Assertions are off!')

To use this approach, you would oviously need to modify your assert calls to use the (NDEBUG || expr) approach, and you would add the two lines to bring in the global, as done in testassertions.m above. This is not the "switch" you are looking for, but it would avoid computing expr, which seems to be the real goal here.

Override with custom assert.m

You can override assert with your own assert.m at the top of your path. Just use varargin and it will work:

function assert(varargin)
end

The first time you run it or rehash your path, you get a warning, then it's fine!

>> assert(false)
>> assert(false,'No error here',[])
>> 

No errors, no warnings.

Override with anonymous assert

Possibly easier to manage is an anonymous assert function with variable inputs and no outputs:

assert = @(varargin) deal;

Here we are using deal with no inputs (nargin=0) because it just does varargout = varargin;.

like image 106
chappjc Avatar answered Oct 06 '22 00:10

chappjc