Perfect use to global variables across functions

16 Ansichten (letzte 30 Tage)
Niveen El Zayat
Niveen El Zayat am 9 Mai 2018
Kommentiert: Stephen23 am 9 Mai 2018
I am working with Monte Carlo Simulation approach, some constants have been fixed at the top of the main script also data is simulated in the main script. I created some functions script files work over estimation and computations. To avoid calling the variables that have been created or fixed in the main file I defined them as global.
Matlab gives me the following warning message, can anybody advise??
Warning: The value of local variables may have been changed to match the globals. Future versions of MATLAB will require that you declare a variable to be global before you use that variable.
  4 Kommentare
Niveen El Zayat
Niveen El Zayat am 9 Mai 2018
John and Stephen, Thanks a lot for your advise. Comment on "You can collect it all into a single struct"
In fact that was the idea I was searching for because I used to do so with STATA when I repeated code over same variables, but I failed to find it in Matlab, I think now I can find it. Lot of thanks
Stephen23
Stephen23 am 9 Mai 2018
"...because I used to do so with STATA when I repeated code over same variables..."
Different languages do things in different ways. If you want to write good code and waste less of your time, then you really need to learn the features of each language. You might be interested to read this:

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Walter Roberson
Walter Roberson am 9 Mai 2018
That particular message occurs when you have a global statement for a variable name that you had already assigned a value to inside the function. For example
G = 5
global G
would generate the message, because the global G that is activated might not have value 5. The above does not mean to initialize G to 5 and then to "promote" G to be global: it means to create a local variable named G with value 5 and then to remove the variable from the workspace and make G refer to the existing value of the global variable G.
No offence intended, but people who do not know this about global variables should probably not be using global variables. Global variables are easy to make mistakes with, and should be avoided.

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by