how to define a global variable in a function file, such that all helper functions in this function file can use this variable?
Afficher commentaires plus anciens
For example, I have following use case. There are bunch of helper functions in func.m file, which will use some global variable const. How can I declare them once, such that all helper functions in this function file can use them?
% func.m file
const = 10;
function res = func()
a = helper1();
b = helper2();
res = a + b;
end
function res = helper1()
res = const^2;
end
function res = helper2()
res = const * 10;
end
Réponses (1)
Cris LaPierre
le 25 Jan 2021
Modifié(e) : Cris LaPierre
le 25 Jan 2021
I'd be careful of using global variables. See this page about nested functions, particularly the section about sharing variables between parent and nested functions.
Using the information provided there, I might rewrite your functions as follows.
% calling script
const = 10;
resOut = func(const)
% func.m file
function res = func(const)
a = helper1();
b = helper2();
res = a + b;
function res = helper1()
% nested inside func, so can access const
res = const^2;
end
function res = helper2()
% nested inside func, so can access const
res = const * 10;
end
end
Catégories
En savoir plus sur C Shared Library Integration dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!