How can I use attribute GLOBAL efficiently?
3 次查看(过去 30 天)
显示 更早的评论
MATLAB Help describes this topic (word "global") very shortly.
I ask it from such question:
M-file as function:
function [y]=y(x) a=2; y=a*x.^2 end
how to force the procedure to modify global variables? that is, after proc. work, some results will be saved in globals and be available for other procedures.
For example, assigning a=2 I wish to keep. But I don't want use simple ways: 1) text file 2) write [y,a] in header, or y=[y; a] in body
If I write global a; a=2
this haven't effect...
and may anybody give good practical code example with and without GLOBAL?
0 个评论
采纳的回答
Jan
2011-3-31
Working with GLOBALs is fragile in all programming languages: It is very hard to find out, where and why the value was set the last time.
Therefore I'd use Paulo's approach ever: "function [y,a]=y(x)" and forward of [a] to all functions, which need it.
Another approach is using a dedicated function to store the value persistently:
function a = Store(Command, a)
persistent a_
switch Command
case 'get', a = a_;
case 'set', a_ = a;
otherwise error('unknown command');
end
Although this has the same drawback as GLOBAL ([a] can be influenced from anywhere), you can at least use the debugger to track changes and usage of [a].
But it is at least possible to use GLOBALs (I avoid using "y" as variable and function name at the same time):
function yValue = y(x)
global a
a = 2;
yValue = a * x .^ 2;
end
Then from the command line or inside another function:
global a
disp(a) % >> nothing
k = y(1:10);
disp(a) % >> 2
4 个评论
Jan
2011-4-1
@Igor: Imagine declaring a variable once as GLOBAL would be enough. Then I insert "global sin; sin=0;" in any M-file. Afterwards no Matlab function would be able to calculate a SIN anymore, because the variable would shadow the function SIN. The same problem would appear for all variables: if "y" is such a brute GLOBAL concerning all functions, any function using this would overwrite the value - e.g. Matlab's MEAN function!
更多回答(3 个)
Paulo Silva
2011-3-31
The way you should always work with is:
function [y,a]=y(x)
if you still want to use global variables you must declare the variable as global everywhere you want to use it (other functions and workspace)
9 个评论
Walter Roberson
2011-3-31
Do not use a variable name which is the same as the name of your function: doing so may lead to unwanted recursion.
David Young
2011-3-31
If you find a real need to use global variables to share data between functions, consider adopting an object-based approach instead. The functions that need to share become methods in a class, and the shared variables become properties of that class.
2 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!