KAHIBARO Bookshelves
Discord Login Register

19.3. Using Relative Paths and the MATLAB Path

Why Paths Matter for Automation

When you start automating tasks in MATLAB, you often want your scripts to run correctly on different computers or in different folders. Hard coding full file locations like C:\Users\Alice\Documents\project\data.csv quickly becomes fragile. If you move the project to another folder or share it with someone else, those absolute paths break.

Using relative paths and understanding the MATLAB path lets your scripts find files and functions in a more flexible way. Relative paths keep file references tied to your project folder instead of to a specific computer. The MATLAB path tells MATLAB where to look for scripts and functions. Together they are essential tools for writing portable automation code.

Absolute vs Relative Paths

A file path describes where a file or folder lives in your file system. An absolute path starts from the root of the file system. A relative path starts from some current location.

An absolute path on Windows might look like

C:\Users\Alice\Documents\project\data\measurements.csv

On macOS or Linux an absolute path might be

/Users/alice/Documents/project/data/measurements.csv

These paths work only if the folder structure and user name are exactly the same. For automation and sharing, that is rarely true.

A relative path describes the location of a file relative to the current folder in MATLAB. For example, if MATLAB’s current folder is project, and inside project there is a subfolder data with a file measurements.csv, then you can refer to it as

data/measurements.csv

MATLAB will interpret this string based on the current folder. If you move the whole project folder to another place, the relative structure is the same, so the script still finds the file.

Current Folder and `pwd`

The idea of a relative path depends on where you are currently located. In MATLAB, the current folder is the base location for relative paths. The current folder is shown in the Current Folder panel and also in the address bar at the top of the MATLAB Desktop.

You can get the current folder from code with pwd, which stands for “print working directory”:

matlab
currentFolder = pwd;

The variable currentFolder now contains an absolute path string like

'C:\Users\Alice\Documents\project'

You can change the current folder from code using cd:

matlab
cd('data');          % go into subfolder "data" relative to current folder
cd('..');            % go up one folder
cd('C:\temp');       % absolute path, Windows example

It is often helpful in automation scripts to set the current folder at the beginning, then use relative paths for everything else.

Relative Path Syntax: `.` and `..`

Relative paths can use special segments to refer to “here” and “one folder up”.

The single dot . means the current folder. A path like

./data/measurements.csv

means “go to the data subfolder of the current folder, then take measurements.csv”. In most cases the leading ./ is optional, so data/measurements.csv is equivalent.

The double dot .. means the parent folder one level above the current folder. For example, suppose your project structure is

project/
project/scripts/
project/data/

If MATLAB’s current folder is project/scripts, but your data is in project/data, you can go up one level then down a different branch:

matlab
filename = '../data/measurements.csv';
T = readtable(filename);

Here, .. moves from project/scripts up to project, then data/measurements.csv moves into the data subfolder.

You can chain .. segments. For example, ../../raw/data.csv goes up two levels from the current folder, then into raw.

Using Relative Paths in File Functions

Many MATLAB functions that read or write files accept either absolute or relative paths. For automation you usually want to pass relative paths that are consistent within your project.

Typical functions include readtable, load, save, imread, audioread, and many others. If you keep your project organized with a consistent folder structure, you can write scripts that refer to files using relative locations.

For example, suppose your project has

project/
project/scripts/processData.m
project/data/input.csv
project/results/output.csv

If processData.m is in project/scripts, and the current folder is also project/scripts when you run it, you might write:

matlab
inputFile  = '../data/input.csv';
outputFile = '../results/output.csv';
T = readtable(inputFile);
% process T here
writetable(T, outputFile);

If you or someone else moves the entire project folder to a new place, the relative structure stays the same, and the script continues to work.

Building Paths with `fullfile`

Hard coding file separators like \ or / can cause problems across different operating systems. MATLAB provides the function fullfile to build paths in a robust way.

fullfile joins folder and file names using the correct separator for the current platform. For example:

matlab
dataFolder = 'data';
fileName   = 'measurements.csv';
filePath   = fullfile(dataFolder, fileName);

On Windows, filePath becomes

'data\measurements.csv'

On macOS and Linux, it becomes

'data/measurements.csv'

You can combine pwd and fullfile to construct absolute paths from a known base folder:

matlab
projectFolder = pwd;
dataFolder    = fullfile(projectFolder, 'data');
filePath      = fullfile(dataFolder, 'measurements.csv');

This is useful when you want to know exactly where files are on disk, but still avoid hard coding the full path in your script.

For automation, a common pattern is to use fileparts and mfilename to build paths relative to the script file itself, rather than the current folder. For example:

matlab
thisFile   = mfilename('fullpath');      % full path to current script or function
[thisFolder,~,~] = fileparts(thisFile);  % folder containing this file
dataFolder = fullfile(thisFolder, '..', 'data');
filePath   = fullfile(dataFolder, 'input.csv');

This approach is more robust, because it does not depend on where the user sets the current folder before running the script.

The MATLAB Search Path: Concept

So far the discussion has focused on paths to data files. The MATLAB path is a separate idea. It is a list of folders that MATLAB searches when you type the name of a function or script without giving its full location.

When you call myFunction like this:

matlab
result = myFunction(x);

MATLAB looks for myFunction.m in the following places, in order:

  1. The current folder.
  2. Any folders that are on the MATLAB path.

If MATLAB does not find myFunction in any of those locations, it reports an “undefined function” error.

The MATLAB path does not control where file functions like readtable look for data. Those still rely on the current folder or the path you supply. The MATLAB path is about finding MATLAB code: scripts, functions, and class definitions.

Viewing and Editing the MATLAB Path

You can inspect the MATLAB path in several ways. The path function returns a single long string with all folders in the search path, separated by a platform specific character. For a more convenient view, you can use path with no output to display it in the Command Window:

matlab
path

To add a folder to the path temporarily, for the current MATLAB session only, use addpath:

matlab
addpath('C:\Users\Alice\Documents\project\scripts');

or with a relative folder:

matlab
addpath('scripts');        % relative to current folder
addpath('../common');      % go up one folder then into "common"

You can remove a folder from the path using rmpath:

matlab
rmpath('scripts');

These changes last until you close MATLAB or clear the path in some other way.

There is also an interactive tool called Set Path, available under the Home tab. It lets you add or remove folders from the path through a graphical interface, and save the changes for future sessions.

Persistent Paths with `savepath`

If you always want certain folders to be available for your MATLAB code, you can save your current search path as the default. First set up the path using addpath or the Set Path dialog. Then call savepath:

matlab
savepath

MATLAB writes your current path configuration to a file, so that the same path is restored the next time MATLAB starts.

For project specific code, it is usually preferable to add paths in a startup script or in a project initialization script, instead of modifying the global default path permanently. This keeps projects separate and reduces the chance of name conflicts.

Using Relative Paths with `addpath`

Just like file paths, addpath can use relative paths based on the current folder. Suppose your project has this structure:

project/
project/code/
project/code/utils/
project/data/

If the current folder is project, and your reusable functions are in code and code/utils, you can add them both to the search path using relative paths:

matlab
addpath('code');
addpath('code/utils');

If you move the whole project folder, those relative paths still refer to the right locations as long as you run the script from inside project.

You can combine fileparts and mfilename to add folders relative to the script location instead of the current folder. This is more reliable for shared scripts that might be run from different starting points:

matlab
thisFile   = mfilename('fullpath');
[thisFolder,~,~] = fileparts(thisFile);
utilsFolder = fullfile(thisFolder, '..', 'code', 'utils');
addpath(utilsFolder);

Here, utilsFolder is defined relative to the folder containing the script, not relative to wherever the user’s current folder happens to be.

Organizing Project Code vs Using the Path

There are two common approaches to organizing project code and making it visible to MATLAB.

One approach is to keep the current folder at the project root, and then add a few key subfolders to the search path. Your main scripts live in the project folder and can call functions in those subfolders. Data files are accessed using relative paths from the project root to the data subfolders.

Another approach is to keep most project code under one top level folder that you add to the path, and then allow MATLAB to find functions there regardless of the current folder. Data files are still best handled with relative paths, usually based on the current folder or the script’s folder.

Whichever approach you choose, avoid adding system wide folders or entire drives to the MATLAB path. That increases the chance of name conflicts and makes it hard to know which version of a function MATLAB is actually calling.

Avoiding Name Conflicts and Path Problems

Because the MATLAB path controls which code MATLAB finds, it is easy to accidentally create conflicts. If a folder on the path contains a file with the same name as a built in function, MATLAB may call your file instead of the built in one.

You can check which function MATLAB is calling with which:

matlab
which sum
which myFunction

If you see that MATLAB is calling the wrong file, you may need to rename your file, adjust the search path with rmpath, or change the folder order on the path.

For automation scripts, keep the path as simple and local as possible. Limit addpath to folders that really contain code you need for that project. If you add folders at the beginning of a script, consider removing them at the end with rmpath to leave the MATLAB environment clean.

Startup Scripts and Project Initialization

To make automated workflows more convenient, you can set up initialization code that configures relative paths and the MATLAB path for you.

A common pattern is to write a small startup.m script in a folder that you always run at the beginning of a session. This script might do things like set the current folder to your main project area, add key code folders to the path, and define commonly used relative paths.

For example:

matlab
% In startup.m
projectRoot = 'C:\Users\Alice\Documents\matlab_projects\myproject';
cd(projectRoot);
addpath('code');
addpath(fullfile('code', 'utils'));

For code that you share, you might instead write a project specific initialization script that other users can run after they download the project. That script can avoid hard coded absolute paths by using mfilename and fileparts to locate the project folder relative to the script itself.

Using such initialization code reduces manual setup and makes your automated tasks more repeatable.

Important points to remember:
Use relative paths like ../data/file.csv so scripts survive folder moves and sharing.
The current folder controls how relative paths are interpreted. Use pwd to check it and cd to change it.
Use fullfile instead of manually typing file separators, to write portable path code.
The MATLAB path is for finding MATLAB code, not data files. Manage it with addpath, rmpath, and savepath.
Keep the MATLAB path small and project specific to avoid name conflicts and confusion about which functions are being called.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Getting Started with MATLAB
    • ☰ 1.1. What Is MATLAB and What Is It Used For
      • ☰ 1.2. Installing MATLAB and Setting Up the Environment
        • ☰ 1.3. Understanding the MATLAB Desktop Interface
          • ☰ 1.4. Command Window, Workspace, and Current Folder
            • ☰ 1.5. Basic Workflow and Running Simple Commands
              • ☰ 1.6. Getting Help and Documentation
              • ☰ 2. MATLAB Language Basics
                • ☰ 2.1. MATLAB Syntax and Expressions
                  • ☰ 2.2. Variables and Assignment
                    • ☰ 2.3. Data Types and Type Conversion
                      • ☰ 2.4. Vectors and Matrices Fundamentals
                        • ☰ 2.5. Creating and Indexing Arrays
                          • ☰ 2.6. Basic Arithmetic and Elementwise Operations
                            • ☰ 2.7. Using Built-In Constants and Functions
                            • ☰ 3. Working with Variables and the Workspace
                              • ☰ 3.1. Creating, Viewing, and Editing Variables
                                • ☰ 3.2. Workspace Browser and Variable Inspector
                                  • ☰ 3.3. Saving and Loading Data Files
                                    • ☰ 3.4. MAT-Files and Importing External Data
                                      • ☰ 3.5. Clearing Variables and Managing the Workspace
                                      • ☰ 4. Vectors, Matrices, and Arrays
                                        • ☰ 4.1. Row and Column Vectors
                                          • ☰ 4.2. Matrix Creation and Concatenation
                                            • ☰ 4.3. Indexing, Slicing, and Logical Indexing
                                              • ☰ 4.4. Matrix Operations vs Elementwise Operations
                                                • ☰ 4.5. Reshaping and Rearranging Arrays
                                                  • ☰ 4.6. Special Matrices and Functions
                                                  • ☰ 5. Basic Programming Constructs
                                                    • ☰ 5.1. Scripts vs Functions
                                                      • ☰ 5.2. Control Flow with if, elseif, else
                                                        • ☰ 5.3. Loops with for and while
                                                          • ☰ 5.4. break, continue, and return
                                                            • ☰ 5.5. Logical Expressions and Relational Operators
                                                              • ☰ 5.6. Best Practices for Clear and Readable Code
                                                              • ☰ 6. Functions in MATLAB
                                                                • ☰ 6.1. Creating Simple Functions
                                                                  • ☰ 6.2. Function Inputs and Outputs
                                                                    • ☰ 6.3. Function Files and the Path
                                                                      • ☰ 6.4. Local vs Global Variables
                                                                        • ☰ 6.5. Anonymous Functions
                                                                          • ☰ 6.6. Organizing Code into Multiple Functions
                                                                          • ☰ 7. Working with Numbers and Math
                                                                            • ☰ 7.1. Scalars and Vectorized Computations
                                                                              • ☰ 7.2. Basic Mathematical Functions
                                                                                • ☰ 7.3. Trigonometric and Exponential Functions
                                                                                  • ☰ 7.4. Complex Numbers in MATLAB
                                                                                    • ☰ 7.5. Rounding, Modulo, and Special Values
                                                                                      • ☰ 7.6. Numerical Precision and Floating Point Considerations
                                                                                      • ☰ 8. Strings, Characters, and Categorical Data
                                                                                        • ☰ 8.1. Character Arrays and String Arrays
                                                                                          • ☰ 8.2. Creating and Manipulating Strings
                                                                                            • ☰ 8.3. Converting Between Data Types and Strings
                                                                                              • ☰ 8.4. Comparing and Searching Strings
                                                                                                • ☰ 8.5. Categorical Arrays Basics
                                                                                                • ☰ 9. Tables, Structures, and Cell Arrays
                                                                                                  • ☰ 9.1. Introduction to Tables
                                                                                                    • ☰ 9.2. Creating Tables and Accessing Data
                                                                                                      • ☰ 9.3. Modifying and Joining Tables
                                                                                                        • ☰ 9.4. Structures and Nested Structures
                                                                                                          • ☰ 9.5. Cell Arrays and Cell Indexing
                                                                                                            • ☰ 9.6. Choosing the Right Container Type
                                                                                                            • ☰ 10. Importing and Exporting Data
                                                                                                              • ☰ 10.1. Reading Text and CSV Files
                                                                                                                • ☰ 10.2. Importing Excel Spreadsheets
                                                                                                                  • ☰ 10.3. Importing Data with the Import Tool
                                                                                                                    • ☰ 10.4. Exporting Data to Files
                                                                                                                      • ☰ 10.5. Working with Image and Audio Files
                                                                                                                        • ☰ 10.6. Basic File Management from MATLAB
                                                                                                                        • ☰ 11. Plotting and Visualization
                                                                                                                          • ☰ 11.1. Introduction to 2D Plotting
                                                                                                                            • ☰ 11.2. Customizing Plots and Axes
                                                                                                                              • ☰ 11.3. Multiple Plots in One Figure
                                                                                                                                • ☰ 11.4. Labels, Titles, Legends, and Annotations
                                                                                                                                  • ☰ 11.5. Plotting with Different Line and Marker Styles
                                                                                                                                    • ☰ 11.6. Saving and Exporting Figures
                                                                                                                                    • ☰ 12. Advanced Plotting for Beginners
                                                                                                                                      • ☰ 12.1. Subplots and Tiled Layouts
                                                                                                                                        • ☰ 12.2. Bar, Scatter, and Stem Plots
                                                                                                                                          • ☰ 12.3. Histograms and Density Plots
                                                                                                                                            • ☰ 12.4. 3D Plots and Surface Plots
                                                                                                                                              • ☰ 12.5. Using plottools and Interactive Editing
                                                                                                                                                • ☰ 12.6. Basics of Handle Graphics
                                                                                                                                                • ☰ 13. Working with Scripts and Live Scripts
                                                                                                                                                  • ☰ 13.1. Creating and Running Script Files
                                                                                                                                                    • ☰ 13.2. Sectioning Code and Running Sections
                                                                                                                                                      • ☰ 13.3. Live Scripts and Rich Text
                                                                                                                                                        • ☰ 13.4. Adding Equations, Images, and Outputs
                                                                                                                                                          • ☰ 13.5. Sharing and Exporting Live Scripts
                                                                                                                                                          • ☰ 14. Debugging and Code Quality
                                                                                                                                                            • ☰ 14.1. Finding and Fixing Syntax Errors
                                                                                                                                                              • ☰ 14.2. Setting Breakpoints and Stepping Through Code
                                                                                                                                                                • ☰ 14.3. Inspecting Variable Values During Execution
                                                                                                                                                                  • ☰ 14.4. Using the Editor Debugging Tools
                                                                                                                                                                    • ☰ 14.5. Using Code Analyzer and Warnings
                                                                                                                                                                      • ☰ 14.6. Writing Clean and Maintainable MATLAB Code
                                                                                                                                                                      • ☰ 15. Basic Linear Algebra with MATLAB
                                                                                                                                                                        • ☰ 15.1. Vectors and Norms
                                                                                                                                                                          • ☰ 15.2. Matrix Addition and Multiplication
                                                                                                                                                                            • ☰ 15.3. Solving Linear Systems with Backslash
                                                                                                                                                                              • ☰ 15.4. Inverses, Determinants, and Rank
                                                                                                                                                                                • ☰ 15.5. Eigenvalues and Eigenvectors
                                                                                                                                                                                  • ☰ 15.6. Using Linear Algebra Functions Safely
                                                                                                                                                                                  • ☰ 16. Data Analysis and Statistics Fundamentals
                                                                                                                                                                                    • ☰ 16.1. Descriptive Statistics and Summary Measures
                                                                                                                                                                                      • ☰ 16.2. Sorting, Filtering, and Grouping Data
                                                                                                                                                                                        • ☰ 16.3. Basic Correlation and Regression
                                                                                                                                                                                          • ☰ 16.4. Simple Data Cleaning Techniques
                                                                                                                                                                                            • ☰ 16.5. Basic Time Series Handling
                                                                                                                                                                                            • ☰ 17. Working with Time and Dates
                                                                                                                                                                                              • ☰ 17.1. Representing Dates and Times
                                                                                                                                                                                                • ☰ 17.2. Creating and Formatting datetime Arrays
                                                                                                                                                                                                  • ☰ 17.3. Date Calculations and Differences
                                                                                                                                                                                                    • ☰ 17.4. Plotting Data over Time
                                                                                                                                                                                                    • ☰ 18. Introduction to Signal and Image Handling
                                                                                                                                                                                                      • ☰ 18.1. Basic Signal Representation in MATLAB
                                                                                                                                                                                                        • ☰ 18.2. Simple Filtering and Transformations
                                                                                                                                                                                                          • ☰ 18.3. Reading, Displaying, and Writing Images
                                                                                                                                                                                                            • ☰ 18.4. Basic Image Transformations
                                                                                                                                                                                                            • ☰ 19. Automation and Scripting Tasks
                                                                                                                                                                                                              • ☰ 19.1. Batch Processing of Files
                                                                                                                                                                                                                • ☰ 19.2. Writing Reusable Utility Scripts
                                                                                                                                                                                                                  • ☰ 19.3. Using Relative Paths and the MATLAB Path
                                                                                                                                                                                                                    • ☰ 19.4. Simple User Interaction with input and disp
                                                                                                                                                                                                                    • ☰ 20. Introduction to Toolboxes
                                                                                                                                                                                                                      • ☰ 20.1. What Are Toolboxes and How to Use Them
                                                                                                                                                                                                                        • ☰ 20.2. Exploring Installed Toolboxes
                                                                                                                                                                                                                          • ☰ 20.3. Finding Functions in Toolboxes
                                                                                                                                                                                                                            • ☰ 20.4. Add-Ons and MATLAB File Exchange
                                                                                                                                                                                                                            • ☰ 21. Best Practices and Next Steps
                                                                                                                                                                                                                              • ☰ 21.1. Organizing Projects and Folders
                                                                                                                                                                                                                                • ☰ 21.2. Version Control Basics with MATLAB
                                                                                                                                                                                                                                  • ☰ 21.3. Performance Tips for Beginners
                                                                                                                                                                                                                                    • ☰ 21.4. Learning Resources and Documentation Path
                                                                                                                                                                                                                                      • ☰ 21.5. Suggested Practice Projects for Beginners