Set variable equal to folder in path

9 views (last 30 days)
Andrew Biehl
Andrew Biehl on 4 May 2020
Answered: Andrew Biehl on 7 May 2020
I am running a script in multiple directories. They are organized like this:
MainDir/SubDir1/SubDir2/AnalysisDir1
I want to store the string "SubDir1" as a variable, which I will later insert into the name of the output files.
Here's how I accomplish this in cygwin:
cd ./../../
SubDir1="${PWD##*/}"
cd ./SubDir2/AnalysisDir
Any help would be much appreciated.

Answers (2)

Steven Lord
Steven Lord on 4 May 2020
Assuming you start off in MainDir:
S = 'SubDir1';
A = fullfile(pwd, S, 'SubDir2', 'AnalysisDir1');
fprintf('Changing directory to %s.\n', A)
cd(A)
  1 Comment
Andrew Biehl
Andrew Biehl on 4 May 2020
Thanks for the code. I don’t think my question was clear. I don’t want to manually assign ‘Subdir’. I want the code to extract ‘Subdir’ from the existing path. Here is my list of Directories. Note that I changed “Subdir1” to “Subdir1a,b,c…”
MainDir/SubDir1a/SubDir2/AnalysisDir1
MainDir/SubDir1b/SubDir2/AnalysisDir2
MainDir/SubDir1c/SubDir2/AnalysisDir3 …
I will run the matlab file using a .bat file which I will use to run multiple different programs in series. For the Matlab portion of the .bat file, I will first change the working directory to the analysis directory (e.g. AnalysisDir1), and then I will run MatlabScript.m within the analysis directory.
I want to have lines of code within MatlabScript.m which will pull SubDir1a (or b,c, etc) out of the path, so that my output can be sent to SubDir1a.txt

Sign in to comment.


Andrew Biehl
Andrew Biehl on 7 May 2020
Are there any other thoughts on this question? Thanks!

Categories

Find more on Search Path in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!