Help with Global Variables

2 views (last 30 days)
Dionisio Mendoza
Dionisio Mendoza on 6 May 2019
Commented: Stephen23 on 6 May 2019
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 Comment
Stephen23
Stephen23 on 6 May 2019
"Is it a good idea to use a global variable,..."
No.
"...or is there a better procedure?"
Yes. Use nested functions or anonymous functions:

Sign in to comment.

Answers (1)

dpb
dpb on 6 May 2019
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.

Categories

Find more on Function Creation in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!