Help with Global Variables

조회 수: 4 (최근 30일)
Dionisio Mendoza
Dionisio Mendoza 2019년 5월 6일
댓글: Stephen23 2019년 5월 6일
I need help with the use of global variables. What happens is that I want to change the value of a variable (the variable is D), which is of a function (the function is called Modeleth) to change the original value of D with these new data: .04 .08 .12 .16 .3.
The objective is to graph using hold on to observe and compare the behavior of the graph.
The document of the function is the one with the name Modeleth and the other document called corridaModelethtarea is the script of how I tried to execute it
Is it a good idea to use a global variable, or is there a better procedure?
Insert the images by the programs do not open ...
Captura.PNG
Captura2.PNG
  댓글 수: 1
Stephen23
Stephen23 2019년 5월 6일
"Is it a good idea to use a global variable,..."
No.
"...or is there a better procedure?"
Yes. Use nested functions or anonymous functions:

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

답변 (1개)

dpb
dpb 2019년 5월 6일
But you define and set D=0 in the function as a local variable inside the function modeleth so nothing outside prior to that matters, global or not.
And, once you declare D as global in the script |corridaModelethtarea then it's as global as it's going to get--there's on point in repeating the same instruction.
If you want to use global D to set other parameters inside the function function modeleth that's certainly one way to do so, but you must then use that copy inside the function as well -- declare it global in the function as well and do not initialize it there--only in the other script.
Alternatively, and somewhat cleaner in terms of avoiding global variables, see the third example in the documentation for ode23 that show how to pass additional parameters to the solved function via an anonymous function that uses the additional argument. NB: to have the function utilize the update variables, the anonymous function has to be created after the new value of D is defined; that value is embedded in the anonymous function itself and not read/associated from the variable when called.

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by