Bug regarding precedence of variables over functions sharing the same name?
5 Ansichten (letzte 30 Tage)
Let's say I have defined a variable called size (I'm just using "size" for the sake of a very simple example). MATLAB correctly goes to my variable instead of the standard function "size" when I type size. However, if I define my variable size in a script, then call that script from a function (such that the variable should exist in the function workspace), then try to reference the variable in the function, MATLAB tries to call the standard size function. Try this simple example. Make a script called yay.m that contains the following single line:
Then make a function called doit.m that calls yay and then tries to access the variable size that yay has made:
It will try to access the size function instead. You can even put a "which size" statement right after the call to yay and it will confirm "size is a variable.", but will still proceed to miss it and try to call the function size instead. What's going on??? Is this a bug in MATLAB?
Paulo Silva am 1 Jul. 2011
I don't see a bug, in scripts your variables are in the same scope has the command line but inside functions like your doit function the scope is just that doit function.
size in yay is a variable, yay is a script
size in doit is a MATLAB function, doit is a function
Ok I must admit that something weird is going on after testing and reading the documentation, matlab seems to be confused about it, when we ask what's size MATLAB says it's a variable but when using size to do something it's the MATLAB function again, MATLAB functions seem to take priority.
global catch %in the first line of your yay script
global catch %in the second line of your doit function
Now catch is equal to 2 inside the function doit
Don't use variables with the same name as scripts or MATLAB functions, if you do use the same names you might get weird problems like the one you found.
Matt Fig am 1 Jul. 2011
I would call it a bug. All variables created in a script should exist inside the workspace from which the script was invoked. The workspace the script YAY was invoked from is the workspace of the DOIT function.
I used this:
function  = doit()
% Calls script yay
where the script yay.m is given by:
size = 2;
A = 6;
pi = 4;
ismember = 9;
Correction. The assignment fails even for ISMEMBER. What is funny is that I get a red M-Lint warning on the call to ISMEMBER but not on the call to SIZE.
Of course any bug that prevents the user from choosing such poor variable names is not a bad bug!
Walter Roberson am 11 Jul. 2011
This is not considered a bug: it is a consequence of the JIT. The documented (somewhere) work-around to it is to initialize the variable before invoking the script file.
If using script files to set variable names to override functions is important to you, then use feature() to turn 'accel' 'off'.