What is the best way to use the same constants in different functions?

9 visualizaciones (últimos 30 días)
Hi
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!
Regards Brian.

Respuesta aceptada

Andrew Reibold
Andrew Reibold el 22 de Jul. de 2013
Editada: Andrew Reibold el 22 de Jul. de 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
...etc etc
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.
  1 comentario
Brian Bak
Brian Bak el 22 de Jul. de 2013
Thanks for you answer.
As an alternative I also found that you can put a '~' at the places of the values you do not need. Lets say you only want const1 and const4 then it is written as: [const1, ~, ~, const4] = constants()

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre External Code Integration en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by