How can I use attribute GLOBAL efficiently?
古いコメントを表示
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?
採用された回答
その他の回答 (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 件のコメント
Igor
2011 年 3 月 31 日
Paulo Silva
2011 年 3 月 31 日
you have to declare global a in the workspace before your code!
global a;a=5;globalexample(4), a
Igor
2011 年 3 月 31 日
Paulo Silva
2011 年 3 月 31 日
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
2011 年 3 月 31 日
@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
2011 年 3 月 31 日
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
2011 年 3 月 31 日
@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
2011 年 3 月 31 日
Paulo==BeingImpolite
ans =
1
Igor
2011 年 4 月 1 日
Walter Roberson
2011 年 3 月 31 日
0 投票
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 日
0 投票
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.
カテゴリ
ヘルプ センター および File Exchange で Startup and Shutdown についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!