Kahibaro
Discord Login Register

Function Files and the Path

Function Files in MATLAB

MATLAB functions that you create are usually stored in separate files. Each file contains exactly one main function, and the name of the file must match the name of that main function. This is the key idea behind function files.

A typical function file is a plain text file with extension .m. For example, if you define a function called circleArea, you must save it in a file called circleArea.m. When you later call circleArea in the Command Window or in another script or function, MATLAB looks for circleArea.m, evaluates it, and returns the result.

Inside a function file, the code begins with a function line, followed by the body of the function. The first function in the file is the main function, and its name must exactly match the file name, including case on case sensitive systems. If they do not match, MATLAB will not find or run your function correctly. Any additional functions defined later in the same file act as local helper functions that are only visible to the main function and are not callable from outside that file.

Function files are different from script files. Scripts do not begin with a function line and do not define a new function name. Scripts run in the base workspace, while function files create their own local workspaces and are invoked by their function name. Keeping functions in their own .m files makes your code modular, reusable, and easier to manage.

How MATLAB Finds Function Files

When you type a name like circleArea(5), MATLAB needs to decide what that name refers to. It might be a variable, a built in function, a toolbox function, or a function you wrote yourself. MATLAB follows a search order to decide which one to use. Variable names take precedence, and if there is no matching variable, MATLAB then searches for a function.

For user defined functions, MATLAB does not search your entire disk. Instead, it only searches a specific set of folders that it knows about. This set of folders is called the search path, or simply the path. Only function files that are located in folders on the path, or in the current folder, are visible to MATLAB when you call them.

The current folder is always searched first (after checking variables), then the folders on the path are searched in order. If MATLAB finds multiple functions with the same name in different folders on the path, it uses the one that appears earliest in the path order. This can lead to situations where a function is overshadowed by another function with the same name located earlier in the path. You can use the which command to see exactly which file is being called. For example, which circleArea tells you the full path to the file that MATLAB will run.

If MATLAB cannot find a function with the requested name in the current folder or any folder on the path, it produces an error that the function is undefined. In that case, you either need to move the function file to a folder that MATLAB can see, or update the path so that MATLAB includes the folder where the file is stored.

The MATLAB Path Concept

The MATLAB path is simply a list of folders that MATLAB searches when it looks for functions, class definitions, and certain other files. You can think of it as a search list. Only files that reside in those folders, or in their subfolders when they are explicitly added, are available by name without extra work.

By default, MATLAB automatically sets up a path that includes its built in functions and toolboxes. These folders are usually located in the MATLAB installation directory and should not be modified manually. In addition, MATLAB sets a default user folder, often a folder like Documents/MATLAB, where you can store your own code. This user folder is typically on the path by default, which is why saving functions there allows MATLAB to find them without extra configuration.

You can view the current path from the Command Window by calling the path function, which returns a long string of folder locations. A more convenient way is to use the graphical Path tool that can be opened from the Home tab in the MATLAB desktop, where it is labeled as Set Path. The Path tool shows all folders currently on the path and lets you add or remove folders and change their order. The order determines priority when multiple functions share the same name.

MATLAB stores the path configuration so that it is available across sessions. If you change the path and then exit MATLAB, your changes are preserved if you save the path. The graphical Path tool provides a Save button for this purpose. There is also a savepath function that saves the current path configuration programmatically. For temporary experiments you can modify the path without saving, in which case MATLAB will revert to the stored path when you restart it.

Adding and Removing Folders from the Path

To use your own function files that are stored in custom folders, you often need to update the path. MATLAB provides commands for this, so you do not need to move files into special locations if you prefer a different folder structure.

The addpath function adds one or more folders to the path for the current session. For example, if your functions are stored in a folder C:\Projects\MyCode, you can run

addpath('C:\Projects\MyCode')

After this command, any function files inside that folder are visible to MATLAB, and you can call them by name from the Command Window or from other scripts and functions. If you want your changes to persist across sessions, you can call savepath after adding folders. Without savepath, the new folder remains on the path only until you close MATLAB.

If you no longer want a folder on the path, you can remove it with rmpath. For example,

rmpath('C:\Projects\MyCode')

removes that folder from the current MATLAB path. Again, use savepath if you want to update the saved path permanently.

Sometimes you have many function files organized inside subfolders. If you want to add a folder and all its subfolders at once, you can combine addpath with genpath, which generates a path string that includes the folder and all its subfolders. For example,

addpath(genpath('C:\Projects\MyCode'))

adds MyCode and all folders contained within it to the path. This is useful for larger projects, but you should use it with some care, because adding deeply nested directories can make name conflicts more likely and can slow down the search for functions.

The Role of the Current Folder

Besides the path, the concept of the current folder is central when MATLAB locates function files. MATLAB always knows one folder as the current working directory. The current folder is displayed in the Current Folder browser in the desktop and is also shown in the address bar at the top of the desktop. When you call a function, MATLAB always checks the current folder first after checking for a variable.

If a function file is located in the current folder, MATLAB can find and run it even if that folder is not listed on the path. This is convenient for small one off scripts and functions when you are working in one project folder at a time. You can change the current folder either by using the graphical interface or by calling the cd function with a folder path.

Because the current folder has high priority in function lookup, it is easy to override built in functions accidentally if you create a file in the current folder with the same name as a built in function. For example, if you create a file called sum.m in the current folder, MATLAB will call your sum function rather than the built in sum. This can be confusing. You can check which function is being used with the which command. For long term code, it is usually better practice not to rely only on the current folder. Instead, organize your functions in dedicated project directories and manage visibility through the path.

Name Conflicts and Function Precedence

Since MATLAB looks for functions using an ordered list of folders, function names can conflict. If two different files share the same function name and are located in different folders on the path or in the current folder, MATLAB has to pick one. The rules for precedence are straightforward. MATLAB first checks whether there is a variable with that name. If not, it looks in the current folder. If it still does not find a match, it searches the folders on the path in the order they appear.

The first function that matches the name is the one that MATLAB runs. Other functions with the same name are effectively hidden, or shadowed. This can lead to subtle bugs, especially if you accidentally create a function that has the same name as a built in function or a toolbox function. For example, naming a file mean.m or fft.m is usually a bad idea.

To diagnose precedence issues, use the which command. If you run which sum, MATLAB shows the full path to the file that it will execute. If there are multiple functions with the same name, you can use which -all sum to list all of them in the order of precedence. This helps you detect whether one of your own files is unintentionally overshadowing a built in function or another user defined function.

If you discover a conflict, you can resolve it in several ways. You can rename your function file to a more specific name. You can adjust the folder order using the Set Path tool so that the correct folder has higher priority. Or you can remove problematic folders from the path if you no longer need them. Avoid reusing common or generic names that are likely to collide with MATLAB’s built in functions.

Organizing Function Files in Projects

As your collection of function files grows, organizing them into projects becomes important. A common approach is to create one top level project folder and then group related functions into subfolders within that project. For example, you might have a main project folder that contains subfolders such as utilities, plotting, and io. Each subfolder contains function files that handle specific categories of tasks.

Within a project, you can either add the main project folder to the path along with all its subfolders by using addpath(genpath(projectFolder)), or you can selectively add only certain subfolders to the path. Selectively adding subfolders can reduce the risk of name conflicts and keep the environment cleaner. Adding entire folder trees is convenient, but you should pay attention to any warning signs of conflicting names.

When sharing a project with others, it is common to instruct them either to set the project folder as the current folder before running scripts, or to call a startup script that uses addpath to configure the path for the project. A simple startup.m file that runs addpath calls can automatically prepare the MATLAB environment when someone enters the project folder or launches MATLAB. This approach is particularly helpful when working with version control or when distributing code to colleagues and students.

MATLAB also provides a concept of a user path, which is a default folder that is on the path at startup. Many users store general purpose utility functions in a folder that is permanently on the path, and then keep project specific code in separate project folders that they add only when needed. Keeping general utilities and project specific code separate can make it easier to manage dependencies and to avoid unintended interactions.

Path Management from Within Code

Sometimes you need to adjust the path dynamically from within your code. For example, a main script might need to add folders containing helper functions when it starts, and possibly remove them when it finishes. This is common for reusable toolboxes or self contained projects that you want to distribute.

In such cases, you can write code that calls addpath using folder paths relative to the location of the current file. You can use mfilename('fullpath') combined with fileparts to obtain the folder that contains the running file, then construct subfolder paths based on that. This avoids hard coding absolute paths that are specific to one computer. For example, you can get the directory of the current file and then call addpath on a subfolder path that you build by concatenation. This approach makes your code portable across machines and user accounts.

You should be cautious about overusing addpath and rmpath inside frequently called functions, because changing the path repeatedly during execution can slow down code and make behavior harder to predict. In many situations it is better to configure the path once, either manually through the Set Path interface or by running a dedicated startup script that sets up the environment before you perform any actual computation.

Important points to remember:
Function files must be saved with .m extension and the file name must match the main function name exactly.
MATLAB finds your functions only if they are in the current folder or in folders listed on the MATLAB path.
The current folder is searched before the path, so files there can override functions in other locations.
Use addpath and rmpath to manage which folders are on the path, and savepath to store changes for future sessions.
Use which and which -all to check which function file MATLAB will execute and to detect name conflicts.
Organize function files into project folders and subfolders, and avoid naming your functions the same as common built in functions.

Views: 5

Comments

Please login to add a comment.

Don't have an account? Register now!