- The first function on an Mfile are global, with a few special exceptions (such as those in a private directory).
- This relates to variables, not functions: Do not confuse the two! Using global variables makes code slower, less deterministic, and much harder to debug.
- If you want to write robust, easy to debug code then do not use global variables: simply pass data as input/output arguments or use nested functions.
how to make a global function ?
158 views (last 30 days)
Show older comments
In my program there is is a function that stores all the values of my circuit,how ever i want to make those values golobal (meanining that i can use this varblues in other scripts ).
1) my question is it possible to make a function global ?
2)and from what i undestand using global command is bad programing could you explain why is that ?
3)and what use insted of global command?
thank you
Answers (1)
Walter Roberson
on 9 Jan 2018
The first function in any function .m file (not script, not classdef) is "global" in the sense of being accessible to any other function. There are exceptions for private methods (in directories named private) and for class directories (you cannot add a @ directory to the path), but otherwise they are already global.
However, the ability to access a function anywhere does not mean that any variable created in the function is available everywhere. Values created in functions only exist while the function is running, with the exception of variables declared persistent (and with exceptions for some cases involving nested functions, or anonymous functions.)
It is a valid programming method to have a function that looks something like,
function r = get_param(param_name)
persistent alpha beta radiation
if isempty(alpha)
alpha = ...
beta = ...
radiation = ...
end
if ~exist('param_name','var') || isempty(param_name) || ~ischar(param_name)
r = [];
else
switch param_name
case 'alpha'
r = alpha;
case 'beta'
r = beta;
case 'radiation';
r = radiation;
otherwise
r = [];
end
end
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!