Help with Global Variables

2 次查看(过去 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 中查找有关 Function Creation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by