Help with Global Variables
2 次查看(过去 30 天)
显示 更早的评论
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](https://www.mathworks.com/matlabcentral/answers/uploaded_files/218183/Captura.png)
![Captura2.PNG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/218184/Captura2.png)
1 个评论
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!