What is the best way to use the same constants in different functions?
3 views (last 30 days)
I am looking for a good way to set and use the same constant variables across different functions. I have tried to use global, save them in a *.m file and save them in a function. The approach of using global and a *.m file are slower than calling a function. I need a fast solution since I am calling the functions many times and therefore I would like to use the function approach or something faster. However, I have 50+ constants and which makes the code bad to look at when calling it as: [const1, const2, ..., const50] = constants()
Furthermore, I do not need all the constants in all programs, but some constants are needed in several different functions so it is not possible just to have several constant functions. I would like to avoid parsing the constants to the functions directly since there are many levels of functions.
Is there are smart way to only get the variables you ask for from a function or is the a smarter way of parsing constants to a function?
Thanks in advance!
Andrew Reibold on 22 Jul 2013
Edited: Andrew Reibold on 22 Jul 2013
Write a function with no inputs that sets all of your constants in a structure, and return that structure. (Using structures because you said you didn't want it to look bad when you had 50 in/outputs.)
Function like this:
[data] = function your_function()
data.const1 = 12
data.const2 = 23
data.const3 = 2334
data.const4 = '1337'
data.const5 = 10000
Then when you need those constants in your code, call the function like this:
data = your_function
Your constants should be loaded in as a structure, when you need constant one, it will be loaded as data.const1
As far as I know, and I could be wrong, you can't really avoid not having the structure name out front, but you can change it to whatever you want.