how to define a global variable in a function file, such that all helper functions in this function file can use this variable?

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)

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)
resOut = 200
% 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

Gefragt:

am 25 Jan. 2021

Bearbeitet:

am 25 Jan. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by