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!