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

回答 (1 件)

Cris LaPierre
Cris LaPierre 2021 年 1 月 25 日
編集済み: Cris LaPierre 2021 年 1 月 25 日
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

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

質問済み:

2021 年 1 月 25 日

編集済み:

2021 年 1 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by