Can MATLAB create subfolders within subfolders, programmatically?

조회 수: 49 (최근 30일)
Brad
Brad 2016년 11월 29일
댓글: Brad 2016년 11월 30일
I’m attempting to create a file structure using the following code;
% Make the Junk folder the current folder
cd Junk;
% Ask the user for the directory to be created in the Junk folder, and
% then make it
New_Dir = input('Enter directory name of this event: ', 's');
New_Directory = fullfile('C:', 'Documents and Settings', 'bonstott', 'My Documents', 'MATLAB', 'Junk', New_Dir);
mkdir(New_Directory);
% Change the current folder to the New_Directory and create the subfolders
cd(New_Directory);
mkdir('Plasma');
% Assign the ID numbers a name and place them in the selected folders.
Num_IDs = input('Enter the number of IDs: ');
for j = 1:Num_IDs
Sub_Dir_Name = input('Enter ID number: ', 's');
mkdir('Plasma', Sub_Dir_Name);
end
% create the subfolders within Plasma
cd(New_Directory);
cd Plasma;
mkdir('Vs L');
mkdir('Vs O');
With New_Dir = Test and Num_IDs = 1, the following structure is created;
C:\Documents and Settings\bonstott\My Documents\MATLAB\Junk\Test\Plasma\
1
Vs L
Vs O
But the desired structure is;
C:\Documents and Settings\bonstott\My Documents\MATLAB\Junk\Test\Plasma\1
Vs L
Vs O
Is there a way to create the desired structure, programmatically?

채택된 답변

Guillaume
Guillaume 2016년 11월 29일
Actually, do not use cd at all. It's a complete waste of time and may cause code to fail since it affects where matlab looks for m files. There is absolutely no point in changing the current directory to create a new directory, since, as you demonstrated yourself, mkdir accepts a parent directory (and if it didn't you could pass the full path of the directory to create anyway).
The root cause of your problem is that the 'VS' directories must be created in the loop, not after, and as subdirectories of the main directory you create in the loop.
So,
New_Directory = fullfile(... %full path of directory. Good way to do it
plasma_dir = fullfile(New_Directory, 'plasma');
mkdir(plasma_dir);
Num_IDs = input('Enter the number of IDs: ');
for id = 1 : Num_IDs
iddir = input('Enter ID number: ', 's');
idpath = fullfile(plasma_dir, iddir);
mkdir(idpath); %not even needed, will be created by the next mkdir anyway.
mkdir(idpath, 'Vs L');
mkdir(idpath, 'VS O');
end
  댓글 수: 1
Brad
Brad 2016년 11월 30일
Guillaume, thanks for the inputs. Much cleaner approach on your part.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by