Is it not suggested to use the same function name as a variable?

15 views (last 30 days)
Hello, I have three questions:
1. Is it not suggested to use the same function name as a variable? For example, if I define a function func in one m file-func.m. Is it possible to use function in main file like func=func(parameters)? I got warned in matlab, and not sure whether it is prohibited.
2. Can I use same parameter in different m files. In one m file, I may use result and function from another m file. Should I define different parameters? Or it is fine to use same parameters, because they will not affect the ones in another m file?
3. How can I define universe parameters that can be used in all m files? It is tiring to include a universe parameter in each m file, and if it is possible that would be great! For example, all my m files will use information, say N, and I do not want to introduce N to each m file, can I define it in main function and make it known to all m files?
Thank you!

Accepted Answer

Walter Roberson
Walter Roberson on 22 May 2012
1. It is not prohibited to use use a variable name that is the same as a function that you call, but if you get into the habit of doing that you are likely to run into situations where you think you are calling the function but you are instead indexing into the variable. You can also run in to some difficult-to-detect problems if a name that is used as a function is redefined as a variable in a script file (MATLAB might continue to use the function instead of realizing it is now a variable.)
2. Using the same parameter name in different functions is not a problem.
3. There is no "universal parameter". You can use "global" statements, but the variable needs to be defined as "global" in each routine it is used, which would be as tiring as what you already have.
One way to fake a universal parameter is to define a function of that name that returns the value you want.
function result = N(varargin)
persistent StoredValue
if nargin > 0; StoredValue = varargin{1}; end
result = StoredValue;
end
N(172); %saves 172 as the result of N
for K = 1 : N %calls upon N and gets the saved value and uses that
...
end
  6 Comments
Walter Roberson
Walter Roberson on 22 May 2012
A name associated with an unchangeable value would be usually be called a "constant".
There is no equivalent in MATLAB to #define, and no equivalent to "extern const"
C Zeng
C Zeng on 23 May 2012
Thanks, Sean! I am just thinking more m files will bring more to compute.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming 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!