How to use global variable as local variable

10 visualizaciones (últimos 30 días)
sneha bharadwaj
sneha bharadwaj el 9 de En. de 2017
Editada: Stephen23 el 2 de Dic. de 2020
I have global variables x,y and z i want to use it as local variables how can i use them?

Respuesta aceptada

Stephen23
Stephen23 el 9 de En. de 2017
Editada: Stephen23 el 9 de En. de 2017
"How to use global variable as local variable"
The best answer is "don't". Good code does not use globals: "I have never seen MATLAB code where globals were the right thing to do.... Most of the time I have seen globals being used it was a situation where the code author did not understand scoping of variables. Rather than pass variables from one function to another, they were just being made global."
If you really want to program using buggy methods (eg using globals), then declare them at the top of your function, exactly as the global documentation shows:
global X Y
Note that using globals is a bad programming practice that will make your code very hard to debug. Passing arguments is much more robust, and is the recommended way of passing data between workspaces:
  2 comentarios
Dan Bindman
Dan Bindman el 2 de Dic. de 2020
Oh yeah please explain to me what method you would use other than Global to deal with 20GB+
data matrices. Are you going to pass that in functions? Beause you are going to double (or more) the memory draw for every pass through! Or am I missing something?
Stephen23
Stephen23 el 2 de Dic. de 2020
Editada: Stephen23 el 2 de Dic. de 2020
"Oh yeah please explain to me what method you would use other than Global to deal with 20GB+ data matrices. Are you going to pass that in functions? Beause you are going to double (or more) the memory draw for every pass through! Or am I missing something?"
You might be missing an understanding of MATLAB's copy-on-write approach to data handling:
Depending on the algorithm and if the code is carefully designed then it is certainly possible to write code that passes data to functions and does not make any copies of it in memory.
If the data are very large you should consider using tall arrays:
If you want any help or further advice on either of these then please ask a question and someone will help you with your specific use-case.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Variables en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by