How can I use attribute GLOBAL efficiently?
Show older comments
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?
Accepted Answer
More Answers (3)
Paulo Silva
on 31 Mar 2011
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 Comments
Igor
on 31 Mar 2011
Paulo Silva
on 31 Mar 2011
you have to declare global a in the workspace before your code!
global a;a=5;globalexample(4), a
Igor
on 31 Mar 2011
Paulo Silva
on 31 Mar 2011
NO EFFECT BECAUSE YOU DON'T READ, I SAID "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)"
YOU REMOVED global a FROM YOUR FUNCTION AND PUT IT IN THE WORKSPACE
Jan
on 31 Mar 2011
@Paulo: You are right. Igor removed the GLOBAL statement from the function, which is a mistake. Such mistakes happen, especially if the author is not familiar with this method at all. I think, we have helped him to learn more.
Paulo Silva
on 31 Mar 2011
I said it in just a few words what he should do and he ignored it, I should have used bold letters, bigger font or whatever. Mistakes happen but those darn NO EFFECTS shouldn't happen.
??? Error using ==> The Computer
Please replace the user of this computer and try again
Jan
on 31 Mar 2011
@Paulo: Let me cite Matt Fig: "... the rest is just fluff".
Igor might be 8 or 88 years old, working with Matlab since 6 hours only, very tired or confused by the the impressive power of Matlab. Anyway, I do not see a reason to be inpolite.
Paulo Silva
on 31 Mar 2011
Paulo==BeingImpolite
ans =
1
Igor
on 1 Apr 2011
Walter Roberson
on 31 Mar 2011
0 votes
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
on 31 Mar 2011
0 votes
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.
Categories
Find more on Language Support 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!