how to make a constant global so all packages files use it?
Mostra commenti meno recenti
hello! I would like to define a constant in such a way all my functions in the package folders use it , how can I do it ?? Thank you in advance .
1 Commento
The MATLAB documentation clearly states "Best Practice: Passing Arguments", which is also trivially easy:
k = 1.234;
myfun(k,...)
other(k,...)
morefun(k,...)
The MATLAB documentation also says "Use global variables sparingly, if at all", which is also what many discussions on this forum also advise: https://www.mathworks.com/matlabcentral/answers/319613-how-to-use-global-variable-as-local-variable
etc, etc
Risposta accettata
Più risposte (1)
Robert
il 26 Feb 2021
You could also define a class with only constant properties. Contrary to Jan's solution, you can access the constants directly, without having to assign all of them to a variable first.
Calling it many times does not result in runtime overhead, like Jan said might be the case for his solution.
classdef Constants
properties (Constant)
g = 9.81
k = 1.234
end
end
Reference the constants using:
Constants.g
Of course, if the Constants class is in one of your packages, you have to include its namespace in the call.
2 Commenti
Would using the reference as
x = Constants.g;
instantiate the object "Constants" though? Or is this a static property?
Rik
il 5 Ago 2021
It is a static property for most intents and purposes.
You could easily see if multiple calls of this type will call the constructor multiple times by putting a disp in the constructor.
Categorie
Scopri di più su Workspace Variables and MAT Files in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!