MATLAB: How to organize all of the sub-functions for the application into a single file

applicationcombinedirectoryexternalfilefunctionmanagemanagementMATLABmultipleorganizescriptsub functionsub-directory

I would like my application to be structured as a main MATLAB file and a second file containing all of the sub-functions. It is easier that way for code management. The only way I can have MATLAB work with external functions (not in the main script) is by having a separate file for each function. I would like to combine all of the sub-functions into a single file.

Best Answer

It is not possible to organize script and function files in the way in MATLAB. When a script or function calls a sub-function, MATLAB first searches for the sub-function in the same file. If MATLAB cannot find the sub-function in that file, the interpreter searches for a file with a file name that matches the name of the called sub-function.
As a result, if a MATLAB file contains multiple functions, the interpreter will only be able to "find" the first function in the file. The only way the interpreter will be able to access the other functions is if the first function in the file calls those functions as sub-functions.
There are two possible workarounds.
Method 1:
Organize the entire application as a single file consisting of several sub-functions. The first function will act as the "main" procedure, and it will call each of the remaining functions as sub-routines.
Method 2:
Create a sub-directory devoted to your application, and place all of the MATLAB files associated with the application in this sub-directory. One of the files will act as the "main" script or function, and each of the other files will contain a single sub-function that the main script will call.