What are variable scopes?

27 vues (au cours des 30 derniers jours)
Anne Nguyen
Anne Nguyen le 16 Oct 2019
Modifié(e) : Stephen23 le 16 Oct 2019
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!

Réponse acceptée

Stephen23
Stephen23 le 16 Oct 2019
Modifié(e) : Stephen23 le 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:

Plus de réponses (1)

darova
darova le 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

Catégories

En savoir plus sur Schedule Model Components dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by