how to define a global variable in a function file, such that all helper functions in this function file can use this variable?
Show older comments
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
Answers (1)
Cris LaPierre
on 25 Jan 2021
Edited: Cris LaPierre
on 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
Categories
Find more on C Shared Library Integration in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!