How to disable statements in MATLAB?

After debugging my MATLAB code, I would like to disable the statements in order to get a little extra speed if possible. (The expression inside the statement is very short and fast, but there are many challenges inside hard loops, so it stacks up. Yes, I have profiled.) How do I do this globally in MATLAB? I am looking for something similar to the definition of NDEBUG in C / C ++ or the inclusion of optimization in Python or the flag -disableassertions in Java. Find / replace assert( with %assert( too ugly for my taste.

+6
source share
1 answer

It occurred to me after the publication of these decisions, which, when effectively disabling statements, do not interfere with the execution of the expression. Perhaps you can use a short circuit of logical expressions ( true || expr ) to avoid evaluating expr . This can be done using global NDEBUG instead of true . That is, use assert(NDEBUG || expr) so that expr not evaluated if NDEBUG is true . For instance,

 % 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 will obviously need to modify your assert calls to use the (NDEBUG || expr) approach, and you would add two lines to enter global , as is done in testassertions.m above. This is not the β€œswitch” you are looking for, but it would avoid expr calculations, which seems to be the real goal here.

Override with user 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 will receive a warning, then this is good!

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

No errors, no warnings.

Override with anonymous assert

It might be easier to control the anonymous assert function with variable inputs and without outputs:

 assert = @(varargin) deal; 

Here we use deal without input ( nargin=0 ), because it just does varargout = varargin; .

+7
source

Source: https://habr.com/ru/post/955723/


All Articles