Now since my friends and I have successfully passed our certification exam to become official MATLAB® professionals, I wanted to share some nifty tricks to deal with optional, missing or false arguments in MATLAB®.
Imagine you have the following function call in MATLAB®:
You expect arg1 to be a string, and
arg2 an integer to indicate how often the string in
arg1 is to be displayed. This code is valid code and if run like so:
But what if the second argument is missing? Or what if the first one is not a string? I will show you how you can use the
assert() function to make default values and throw an error if something went wrong.
Calling the function with an argument missing is perfectly valid in MATLAB®:
Yet MATLAB® will complain, that the variable
arg2 has not been defined. You can test for this case using the
exist() function and (in case the variable does not exist) assign a default value, e.g. 1:
There, now the code will run and print a single line of "Hello World!".
Testing for datatype
Luckily MATLAB® can display a variety of datatypes using the
disp() function. Yet if you want to make sure that only strings (or any specific datatype for that matter) are passed, then it may be worth raising an error and stopping the code execution. The function
assert() is perfect for this case! It takes up to three inputs, where:
Specifies the all-clear condition
Is an error identifier
Is an error message (shown to the user)
So if we wanted to make sure, that only strings are passed as
arg1, then we can write:
Now when calling the function and passing e.g.
pi for the 1st argument, then the user will receive a nice error message stating, that the 1st argument is not a string, and the execution stops. It is common convention, to use a function hierarchy specific error ID, so that it is unique and can be traced back. It is worth mentioning, that the "all-clear" condition is the test for when everything works as it should, i.e. when no error should be thrown. Before that I used to throw exceptions inside an if-statement, making the code do the exact opposite. Doing it with
assert() on the other hand is much cleaner.
With these two features, I could rewrite my entire PhD's code in a very quick manner and make it much more robust in comparison to previous iterations. Now, my code is also more flexible and much neater than before. I hope this hint will serve you as well as it did serve me.