How can I create paths relative to a specific folder to facilitate moving project folders to other locations?
조회 수: 32 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
David Goodmanson
2018년 8월 28일
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.
댓글 수: 4
추가 답변 (2개)
Sean de Wolski
2018년 8월 28일
mfilename('fullpath'), fullfile, fileparts, pwd are my best friends for this type of work.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!