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

33 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 24 Apr. 2018
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.

Weitere Antworten (0)

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by