Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does scoping in Matlab work?

Tags:

scope

matlab

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.

like image 890
sebhofer Avatar asked Oct 25 '12 16:10

sebhofer


People also ask

What is scoping function used for?

Scoping is determining where variables, functions, and objects are accessible in your code during runtime. This means the scope of a variable(where it can be accessed) is controlled by the location of the variable declaration.

What is a scope of a variable?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.

How do I change the number of ports on a scope in MATLAB?

To specify the number of input ports: Open a scope window. From the toolbar, select File > Number of Input Ports > More. Enter the number of input ports, up to 96.


1 Answers

MATLAB parses the function before it's ever run. It looks for variable names, for instance, regardless of the branching that activates (or doesn't activate) those variables. That is, scope is not determined at runtime.

ADDENDUM: I wouldn't recommend doing this, but I've seen a lot of people doing things with MATLAB that I wouldn't recommend. But... consider what would happen if someone were to define their own function called "false". The pre-runtime parser couldn't know what would happen if that function were called.

like image 58
Brett Shoelson Avatar answered Oct 05 '22 23:10

Brett Shoelson