What are variable scopes?

조회 수: 26 (최근 30일)
Anne Nguyen
Anne Nguyen 2019년 10월 16일
편집: Stephen23 2019년 10월 16일
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