Number of Files for a Program Script
11 次查看(过去 30 天)
显示 更早的评论
I have a script where I have called a function. I have defined this function in a separate file to the main script - does that make sense ? The code for the main script works perfectly fine so the function must be defined and used correctly. However, when I run the script containing the function, it doesn't work due to errors. This is expected right ?
Also, is it best practice to have a separate script as I have done for my function ? (separate to the script for the main program where the function is called).
0 个评论
回答(1 个)
Walter Roberson
2023-3-7
编辑:Walter Roberson
2023-3-8
Functions in separate files are potentially reusable, which is a good thing.
Functions in the same file are often convenient.
Functions in the same file can offer some guarantees about where exactly the function will be resolved from. For example suppose your script calls MyFun in the same directory as your script but someone is in a different current directory when they run the script: can you be sure that the MyFun in the same directory is the MyFun that will be used? (Answer: No, not unless you used private/ subdirectory). So putting into the same file gives a level of certainty.
5 个评论
Walter Roberson
2023-3-8
If you run a function by itself, and it is a function that requries inputs, and you do not provide the inputs, then you would (typically) receive an error message.
The issue is not with it being in a separate file: the issue is with correct inputs being required. Which is a problem whether it is in the same file or a different file.
Note: there is one sort-of- exception:
If you have a function that defines a function inside of it, like
outer()
function outer
disp('outer here')
inner();
function inner
disp('inner here')
end
end
then variables that are defined in the outer function before calling the inner function can be "shared" with the inner function. In that particular case, moving the inner function to its own file can result in it no longer having access to the variables.
Oh, and of course if you move a function to its own file, then it can no longer access other functions defined in the same file.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Search Path 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!