How to declare a variable in the "main" script such that it is available to all functions without passing the argument

14 views (last 30 days)
Hi,
Question: I want to assign variable a value (a constant) in the main workspace, and make it available to all the functions called by this script without passing this particular argument to the functions.
Bigger picture: I typically declare a few variable (and assign them constant value) in the main script, and then pass those to all the functions. However, these values do not change ever.
Thus, I was wondering if it is possible declare these variables in a certain way in the main script such that they are available to all the functions called by the script without actually passing them as arguments to the functions.
Thanks in advance for your help.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Jun 2012
No. It violates the principle of variable hiding that "workspaces" were implemented for.
You could declare all of your variables to be global, and then global them in each function that needs them. This is, as you might imagine, not very pretty. And it is prone to problems where one of the functions has a logic error that ends up changing the global variables.
The way to get each variable visible without violating information hiding is to declare each of the variables as its own function (in its own .m) that returns the appropriate constant value. Then as long as those functions are on the path, they would be visible. An example of this is pi, which is implemented as a function rather than as a constant known to the parser.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!