MATLAB: Shadowing built-in functions

built-innameshadow

It is a well known problem from the forums, that the name of a built-in function is used for a variable and later, perhaps in another script, the behavior becomes unexpected:
sum = 1:10;
...
sum(1:5) % replies [1,2,3,4,5] instead of 15
If a function was used before, MLint shows a warning (at least in my Matlab version):
clear('sum');
a = sum(1:5);
sum = 1:10;
This happens for common names like: max, min, sum, i, j, line, text, input, …
It seems obvious to prevent these problems by applying the general rule:
  • Never shadow built-in functions by variables!*
But nobody can remember the names of all built-in functions, most of all if they belong to toolboxes not installed on the users computer. And is the name "xbuffer" really smarter or safer than "buffer"?!
We could create a tool, which compares all names of (not dynamically created) variables with all documented toolbox functions and show a warning for all collisions. But I'm not convinced that the time required to check the heap of warning messages is worth to avoid the rare (but ugly) real collisions.
Which strategy do you use or suggest to reduce naming collisions?

Best Answer

I am not using packages either (yet), but I would love to have an alternate version of ADDPATH which would mount folders as packages (basically just generating a name space). It would also be interesting to be able to set MATLAB in a mode where its toolboxes must be "mounted" as packages. E.g.
janLib = addpathpack( '/cedric/matlab/libs/JanLib' ) ;
statTbx = tbxloadpack( 'Statistics' ) ;
reg_jan = janLib.regress( ... ) ;
reg_stat = statTbx.regress( ... ) ;
which -all regress
'regress' not found.