What are variable scopes?

29 次查看(过去 30 天)
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!

采纳的回答

Stephen23
Stephen23 2019-10-16
编辑:Stephen23 2019-10-16
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:

更多回答(1 个)

darova
darova 2019-10-16
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

类别

Help CenterFile Exchange 中查找有关 Schedule Model Components 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by