Why the function file SHOULD have the same name as the first function in the file?
33 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
GIorgi Tsutskiridze
el 24 de Abr. de 2018
Comentada: Ajay Vishwakarma
el 4 de Abr. de 2020
"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:
- Why the function file SHOULD have the same name as the first function in the file?
- Script files cannot have the same name as a function in the file? Why? What will go wrong?
0 comentarios
Respuesta aceptada
Walter Roberson
el 24 de Abr. de 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.
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Whos en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!