What are variable scopes?
89 views (last 30 days)
Stephen23 on 16 Oct 2019
Edited: Stephen23 on 16 Oct 2019
Consider that inside some function you define some variable, e.g.:
X = 3;
You might then ask yourself, now that I have defined it, where can I use that variable?
Can I use it from inside the same function? (yes, once it has been defined)
Can I use it from the base workspace? (in general, no)
Can I use it from inside another function? (in general no, but in some cases yes...).
The "variable scope" refers to the set of rules that let you know where that variable can be used:
For example, nested functions are very useful in many situations, and one of their main features is that variables defined in the "parent" workspace can be use in the nested functions' workspace/s:
X = 3; % the scope of X includes both MYMAIN and MYNEST.
X = X+1 % the scope of X includes both MYMAIN and MYNEST.
Y = 0; % the scope of Y is MYNEST only.
A similar concept also applies to functions (which can be saved on the MATLAB Search Path, or saved in a private folder, or as a function handle within some workspace/s, etc).
More Answers (1)
darova on 16 Oct 2019
Example: sections between function .. end are scopes of variables
x = linspace(0,2);
y1 = f1(x);
y2 = f2(x);
function y = f1(x)
% can't acess 'b'
a = 2;
y = x.^2 + a;
function y = f2(x)
% can't acces 'a'
b = 3;
y = y.^2 * b;