how to define a global variable in a function file, such that all helper functions in this function file can use this variable?
Ältere Kommentare anzeigen
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
Antworten (1)
Cris LaPierre
am 25 Jan. 2021
Bearbeitet: Cris LaPierre
am 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
Kategorien
Mehr zu C Shared Library Integration finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!