Global variables in functions

조회 수: 3 (최근 30일)
farheen asdf
farheen asdf 2017년 9월 11일
댓글: Image Analyst 2019년 10월 7일
I have been trying to use global variables so I can make changes to the said variable in different functions but I can't seem to do it. It seems like the second function does not work. Please help.
function one=new1()
clc
clear global
global m
m=0;
disp('soup')
function hamburger=eat()
m=m+1
disp('sandwich')

채택된 답변

Image Analyst
Image Analyst 2017년 9월 11일
편집: Image Analyst 2017년 9월 11일
Get rid of the "clear global" function in new1(), which blew away your existing globals, and add "global m" to eat():
function one=new1()
global m
clc
m=0;
disp('soup')
function hamburger=eat()
global m
m=m+1
disp('sandwich')
And the variables are only global for the functions that actually have the "global m" line in them, not to other functions that don't have that line.
  댓글 수: 3
farheen asdf
farheen asdf 2017년 9월 11일
The second function is still not working. I know this because the disp('sandwich') command is not working and the value of m is not increasing either
Image Analyst
Image Analyst 2017년 9월 11일
It must not be getting called. Set a breakpoint inside eat() and start your program. See if it stops there. It probably doesn't which means that eat() never gets called. Step through your program from earlier to see what lines of code get executed and try to figure out where you're calling it and why program execution never reaches that line of code.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

dpb
dpb 2017년 9월 11일
>> help clear
...
| clear GLOBAL removes all global variables.
...
However, using global is not recommended as a general programming practice; you don't show enough context to see why there's any reason should be using one here so I'd suggest not doing so.

Raja Awais Liaqait
Raja Awais Liaqait 2019년 10월 7일
I want help in the following code.
global min_realvar ;
global max_realvar ;
Firstly, I want to get the value of these variables and secondly i want to write them in such away that I can give the values of these variables as an input.
  댓글 수: 1
Image Analyst
Image Analyst 2019년 10월 7일
You already HAVE them since you put the global line in your workspace. No need to do anything more. Get them into another variable by referencing them.
someOtherVariable = min_realvar * 500 + 123424; % Whatever....
If you want, you can just pass them in as variables in the input argument list. Or you can write them to a disk file and pass the filename.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by