6

Since Matlab is interpreted, typically spend a lot of time at the beginning of the function enforcing the function signature. For example

if nargin ~= 2; error('must provide two input args a and b'); end
if a < 0||a ~=floor(a); error('input arg1 must be positive non-zero integer'); end 
if ~isa(b,'cell') ...

Is it better to use Matlab's assert() for this instead? If not, when is the appropriate time to use assert() in Matlab?

There is a great discussion on using assert in production code here but I am not certain this applies to interpreted code. Likewise, another good discussion here and I agree with @Dan Dyer regarding assert to express belief about the current state. However, looking at a similar discussion for Python here folks say, only use assert for situations that should never happen (like exceptions for exceptional cases) which is a little contradictory w.r.t. the previous references.

Maybe this is more a question about the role assert plays in interpreted languages and less about Matlab.

Community
  • 1
  • 1
brown.2179
  • 1,750
  • 1
  • 12
  • 15
  • I write matlab code to do alot of prototyping. I'm not sure what the "proper" usecase is, but I essentially go with the belief-of-current-state interpretation, and use them often. I haven't noticed performance issues when profiling in any reasonably new version of matlab. I like how clean they are in code for checking behaviour often. However, I rarely do any production code in matlab :) – adalca Nov 26 '14 at 22:17

3 Answers3

4

For the most part, there is no difference between

assert(X,...)

and

if (~X)
    error(...)
end

and your choice between them is a matter of convenience or style.

The distinction between non-production and production code in MATLAB-based projects is often not the same as the distinction in projects based on other languages.

This is partly because, as you say, MATLAB is typically interpreted rather than compiled; although it's possible to produce applications using MATLAB Compiler or the Builder products that, although not strictly "compiled", do not have visible source code and cannot be debugged. For those sort of applications you would need to handle exceptions and errors just as carefully as you would with a compiled language.

It's also partly because "production" often means something different for projects that use MATLAB than it does for projects in other languages; for example, it might mean that the MATLAB code is automatically converted to C for deployment to a car engine controller, or it might mean that some MATLAB code was running a financial forecasting model and writing results to a production database.

There is a special case where assert should be used rather than if..error..end, which is when you're using MATLAB Coder to generate C code from MATLAB code. MATLAB Coder inspects assert statements in MATLAB code to infer properties of the variables it needs to convert to C, and can generate better C code if it can assume facts about variables that you assert (such as array sizes and types).

One last point: for the specific activity you mention, enforcing a function signature, I would use neither method - inputParser is typically more robust and consistent (although a bit verbose), but more importantly it encourages you to design the function signature well in the first place.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64
3

Another perspective for this issue is running time. Usually, you expect your code to work without errors. This means that you don't care about the miliseconds it takes Matlab to produe an error, but only the logical test.

here is the code I used for comparison:

function o=test

a = 2;
o = [0 0];

tic;
if a~=2
error('a is not 2')
end
o(1) = toc;


tic
assert(a==2,'a is not 2')
o(2) = toc;

now, let's run this function enough times to get good statistics:

for i=1:10000
o(i,:) = test;
end
mean(o)

and the results:

ans =

1.0e-05 *

0.0088 0.3548

the bottom line:

assert is much more slow than if-else.

NoamG
  • 137
  • 9
2

The way MATLAB handles assertions means that, from a user's perspective, there is no difference between the statements:

if error_check == false
    error('function:state','Error message');
end

and

assert(error_check==false,'function:state','Error message');

Both result in the same output shown to the user, and the same data being stored in lasterr. Both are caught by a try-catch block. Based on a very quick and dirty test, I would tentatively claim that assert is ~5% slower than error (though this doesn't really make a huge difference in the large scheme of things). As a result, the only real difference is to the programmer/maintainer of the code, which makes it largely a stylistic choice.

Both assert and error have their pros and cons. assert looks a bit cleaner and takes less space, but it's not necessary as obvious what is happening at first glance. For my personal use, I would prefer the error case, because I can put a breakpoint on the line with the error call, and it will only break there if the error is about to be thrown - this can't be done as easily as with the assert message (you can use dbstop in file if error, but this potentially has its own problems). I can also stick debugging code in the if-statement to print information about the program state before the error is thrown.

MrAzzaman
  • 4,734
  • 12
  • 25