Blog
Matlab syntax tricks

By Raphaël - December 18th, 2016

Matlab

0 Comment

Flow control: for and switch
Operator overload

Packages

Using packages for resolving name conflicts

Name conflict is a recurrent source of errors. It usually happens when one names a variable or - worse - a function with the name of a Matlab function.Though it is really tempting to name variables min, dir or date, it's generally a bad practice as the built-in functions min, dir or date are then shadowed, i.e. unaccessible in the scope where the newly created variables are defined. It can lead to bugs that are very difficult to understand.

For variables, one way to circumvent the problem is to use a structure. For instance, it you want to define two variables min and max out of a random vector, you can place them into a structure:

>> v = rand(100,1);
>> S = struct('min', min(v), 'max', max(v));

and you can access these values with S.min and S.max.

For the record, note that the variables i and j are by default both equal to the complex number $\sqrt{-1}$. However they are redefined in most of the Matlab programs, so it is recommended for this only case not to use the default variables, but instead to systematically use an unambiguous definition like sqrt(-1).

For functions or classes, packages represent a similar solution. For instance, to disambiguate your own save function from the built-in save, simply place it in a folder starting with a plus sign, say +myPack like that:

and if this folder is referenced in Matlab's path your function is now called by:

myPack.save()

You can put classes in packages and create packages of packages, so don't hesitate to use it everywhere. It's a very simple and powerful way to organize your programs' architecture, and you are guaranteed to avoid shadowing issues.

A note on distributed packages: though it doesn't seem to be documented, one can define multiple packages with the same name (homographs) at different locations of the filesystem and - provided they are referenced in matlab's path - they get merged into one single namespace, with all the content acessible. It can be convenient, but be aware that the risk of shadowing reappears if you use this feature.

Flow control: for and switch
Operator overload

Comments

There are no comments on this post so far. Write a comment.