Why the function file SHOULD have the same name as the first function in the file?

조회 수: 30 (최근 30일)
In the MATLAB documentation in in the basics of function there is written:
"You can save your function:
  • In a function file which contains only function definitions. The name of the file should match the name of the first function in the file.
  • In a script file which contains commands and function definitions. Functions must be at the end of the file. Script files cannot have the same name as a function in the file. Functions are supported in scripts in R2016b or later.
My question is twofold:
  1. Why the function file SHOULD have the same name as the first function in the file?
  2. Script files cannot have the same name as a function in the file? Why? What will go wrong?

채택된 답변

Walter Roberson
Walter Roberson 2018년 4월 24일
In MATLAB, there is a special rule for the very first function in a function file. In that one case, if the name of the file and the name of the function differ, then MATLAB will use the name of the file as the function name, and it will not be available under the name given in the function statement. This is confusing and can lead to problems, so it is recommended not to use this feature.
The implementation of functions inside of script files is much like as-if there had been a "function" statement at the beginning of the file that used the file name as the function name. This analogy is not accurate with respect to which workspace is used by the script, but it works with the scoping rules and all the debugger and help facilities that can reference a function inside a file (something that you cannot normally do from the outside). If the script name and the function name were the same that would lead to a name conflict. MATLAB detects the situation and simply refuses to permit execution, same as if you had a syntax error that it was unable to compile.

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by