Can MATLAB create subfolders within subfolders, programmatically?

104 ビュー (過去 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 件)

Community Treasure Hunt

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

Start Hunting!

Translated by