Alex Rivera | Logout

How does scoping in Matlab work?

Asked 2012-10-25T16:34:52.830
14

I just discovered (to my surprise) that calling the following function

function foo()
if false
   fprintf = 1;
else
  % do nothing
end
fprintf('test')

gives and error Undefined function or variable "fprintf". My conclusion is that the scope of variables is determined before runtime (in my limited understanding how interpretation of computer languages and specifically Matlab works). Can anyone give me some background information on this?

Edit

Another interesting thing I forgot to mention above is that

function foo()
if false
   fprintf = 1;
else
  % do nothing
end
clear('fprintf')
fprintf('test')

produces Reference to a cleared variable fprintf.

Edit
Report

1 Answer

8

It seems that the first time the MATLAB JIT compiler parses the m-file, it identifies all variables declared in the function. It doesn't seem to care whether said variable is being declared in unreachable code. So your local fprintf variable immediately hides the builtin function fprintf. This means that, as far as this function is concerned, there is no builtin function named fprintf.

Of course, once that happens, every reference within the function to fprintf refers to the local variable, and since the variable never actually gets created, attempting to access it results in errors.

Clearing the variable simply clears the local variable, if it exists, it does not bring the builtin function back into scope.

To call a builtin function explicitly, you can use the builtin function.

builtin( 'fprintf', 'test' );

The line above will always print the text at the MATLAB command line, irrespective of local variables that may shadow the fprintf function.

answered 2012-10-25T17:27:30.830

Your Answer