MATLAB: How to create paths relative to a specific folder to facilitate moving project folders to other locations

path

Hello everyone!
I would like to find a better way to use paths in Matlab. I often use Matlab scripts to postprocess data, for example by going through many text files and reading their content into Matlab for further analysis. The "problem" I have is that when I have my files in very nested locations and I move the folder containing the files and the script, I have to re-specified the whole path again in the script. I would like to specify the location of the txt files to read relative to the folder that contains the script. How can I achieve this?
Example of project folder:
C:\Users\myusername\Documents\subfolder1\subfolder2\subfolder3\myProject_Folder
'myProject_Folder' contains my txt files in a subfolder:
C:\Users\myusername\Documents\subfolder1\subfolder2\subfolder3\myProject_Folder\txt_files_Folder
and a script, for example
script.m
In script.m I have these lines for example:
outputDir = 'C:\Users\myusername\Documents\subfolder1\subfolder2\subfolder3\myProject_Folder'; %same as Project Folder
txt_files_path = ' C:\Users\myusername\Documents\subfolder1\subfolder2\subfolder3\myProject_Folder\txt_files_Folder'
I would like to have \myProject_Folder as the root folder, so that when I move myProject_Folder and its subfolders to another computer I do not have reenter all the paths again in script.m.
Thanks in advance!
Best regards,
Adriel Perez

Best Answer

Hi Adriel,
Here's one approach, concatenation
% give the path a short name, the idea is on the computer you only have to specify this once
outD = 'C:\Users\myusername\Documents\subfolder1\subfolder2\subfolder3\myProject_Folder';
% then
txt_files_path = [outD, '\txt_files_Folder']
txt_files_path2 = [outD, '\new_txt_files_Folder2']
% and so forth.
You can also make use of the cd function. In my case
Cpath = cd
Cpath = 'c:\users\dave\tech\matlab'
which is a string you can concatenate with something else as with outD, or lop part of it off.
If you have a home base and want to go to the end of some path and temporarily make it the local directory you can do
home_path = cd % save your location
% and
cd(txt_files_path)
Then you can read files in and out locally with no path prefix. After that, cd(home_path) takes you back from whence you came.
Lots of possibilities, this is kind of the 'original' way and if there are more sophisticated ways I imagine others will weigh in.