Script vs Function with no input/output
205 ビュー (過去 30 日間)
Sometimes I have to write a function ad-hoc for a script purpose. Usually I was simply creating a new .m file containing the function.
In order to increase the robustness of my code and avoid a crowd of small .m files roaming around i'm starting considering to exploit the ability of function files to include sub-functions directly in their inside. To exploit this ability however I have to declare the whole script as a function with no input and no output.
Therefore, instead of having:
I create a single file
Of course in this case it seems useless. But sometimes this allows to have only one file instead of 5, 10 or maybe even more that can be shared more easily and are more "compact". (Indeed this kind of behavior can be done natively in other languages such as Python)
Now my question is: except for the "usual" care that have to be put in place when debugging a function and not a script due to the different workspace the variable resides into; is there any drawback you can spot?
Thank you for your opinion. Regards, Luca
Walter Roberson 2015 年 11 月 2 日
functions are usually better than scripts.
Depending on the exact MATLAB release and the complexity of the code and what the code does, there have been some cases where a script could be marginally faster than a function. Single-command scripts can potentially be faster than functions due to function-call overhead. For anything longer, functions are almost always faster.
There have also been some cases, historically, where there have been subtle errors in code interpretation due to the Just In Time optimizer being applied to functions but not to scripts. It happens. It is not at all common.
You do have to watch out for calls such as ode45 where Way Back (like MATLAB 5 and earlier) the way to pass the names of routines to call was as strings, whereas everything newer using function handles is preferred. If you do have something coded using a string as a routine name, and you move the function that is designated to become a function in the same file, then the routine that is doing the calling will not be able to find the function. When functions to call are named by strings, then the function has to have its own .m function file (because the expression that is executed to find the function from the string is executed in the base workspace). The real fix is to convert the call to @ syntax, as that syntax is fine with looking in the same file.