What are variable scopes?
29 views (last 30 days)
Show older comments
I looked at the articles on MathWorks, and I still do not understand variable scopes. Can someone please give me a simpler definition of what variable scopes are, and why they are important? Thank you!
0 Comments
Accepted Answer
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:
function mymain()
X = 3; % the scope of X includes both MYMAIN and MYNEST.
...
function mynest()
X = X+1 % the scope of X includes both MYMAIN and MYNEST.
Y = 0; % the scope of Y is MYNEST only.
end
...
end
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).
See also:
0 Comments
More Answers (1)
darova
on 16 Oct 2019
Example: sections between function .. end are scopes of variables
function main
x = linspace(0,2);
y1 = f1(x);
y2 = f2(x);
plot(x,y1,x,y2)
end
function y = f1(x)
% can't acess 'b'
% disp(b)
a = 2;
y = x.^2 + a;
end
function y = f2(x)
% can't acces 'a'
% disp(a)
b = 3;
y = y.^2 * b;
end
0 Comments
See Also
Categories
Find more on Schedule Model Components in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!