Number of Files for a Program Script

11 vues (au cours des 30 derniers jours)
Kimi Raikonnen
Kimi Raikonnen le 7 Mar 2023
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).

Réponses (1)

Walter Roberson
Walter Roberson le 7 Mar 2023
Modifié(e) : Walter Roberson le 8 Mar 2023
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 commentaires
Walter Roberson
Walter Roberson le 8 Mar 2023
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()
outer here inner here
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.
Kimi Raikonnen
Kimi Raikonnen le 8 Mar 2023
Okay thanks for your help. I now defined the function in the script where I called it in the same file.
Question: where would it be best to define the function?
I defined it at the end / bottom of my program after I called it. Is this okay ? Or would you recommend defining it elsewhere in the program ?

Connectez-vous pour commenter.

Catégories

En savoir plus sur Search Path dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by