Informazioni

Questa domanda è stata definitivamente chiusa e trasferita nelle Discussions.

Magic strings and numbers in Matlab

Jan
Jan il 24 Lug 2013
Some of Matlab's toolbox functions are affected by magic strings or magic numbers, which are strings or numbers with a deeper meaning besides the normal value. Both are considered as bad programming patters, because they provoke confusions, when the magic keys appear with the normal meaning by accident. See http://en.wikipedia.org/wiki/Anti-pattern
Example 1:
clear('myVariable')
clear('variables')
While the 1st clears the variable myVariable, the later clears all variables. Here 'variables' has a meta-meaning. The problem appears, when 'variables' is an existing variable:
a = 1;
variables = 2;
clear('variables')
disp(a) % >> 1
Only variables is cleared, which cannot be understood directly when its definition is 1000 lines before.
Example 2:
uicontrol('String', 'default')
This creates a button with the empty string '' instead of the expected 'default', because this is the magic string to invoke the default value get(0, 'DefaultUIControlString'). The same concerns properties of other graphic objects also, e.g. the 'name' property of figure or the string of uimenu. There is a workaround which allows the user to display 'default': Simply use '\default'. Unfortunately this is doubled magic, because in consequence it is impossible to display the string '\default'. Obviously a bad idea.
Example 3:
Graphic handles are doubles (although gobject of the new R2013a seems, like this is subject to changes? [EDITED: Yes, it changed with HG2 in R2014a]). But then a handle can be confused with data:
a = axes; % e.g. 0.0048828125
plot(a, 2, '+')
But you cannot draw the point [0.0048828125, 2] by this way, because the 1st input is considered as handle of the parent. Here all possible values of handles are magic. Collisions are very unlikely, but there is no way to avoid them reliably - as long as handles have the type double.
Question:
Which functions are concerned by magic values? What are the pitfalls and workarounds?

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by