필터 지우기
필터 지우기

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

조회 수: 5 (최근 30일)
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!

채택된 답변

Walter Roberson
Walter Roberson 2012년 5월 22일
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
Walter Roberson
Walter Roberson 2012년 5월 22일
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 2012년 5월 23일
Thanks, Sean! I am just thinking more m files will bring more to compute.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by