MATLAB: How to use global variable as local variable
globallocal
I have global variables x,y and z i want to use it as local variables how can i use them?
Best Answer
"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 theglobal 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:
You can do this witheval, but you shouldn't. Use a cell array instead.
(I have taken the liberty of adapting some ofStephen Cobeldick's thoughts on this topic) Introspective programing (eval and other functions like it) is slow, andthe MATLAB documentation warns specifically against it. Usingeval is slow, makes debugging difficult, and removes all code helper tools (code checking, syntax hints, code completion, variable highlighting, etc.). A longer discussion can be foundhere. If you are not an expert and you think you needeval, there are probably better solutions to your problem. Also, if you are not an expert, you might find interesting and helpful hints onthis page (and if you are an expert, you can still learn from it).
Best Answer