Problem with making a new directory

I created a code to save figures for each test for 5 subjects. It gives a warning that the subfolder already exists. So I tried to use if statements, and for the directory 'Data_examen1' it worked. But if I include making the subfolder also in my if-statement. It gives an error. I understand what's going wrong here... But I can't figure out how to get rid of the warning...
for welke_pp=1:5 % for 5 subjects
...
for i_testen=1:5 % for 5 measurements
...
if ((i_testen == 1) && (welke_pp == 1))
mkdir Data_examen1 %make new directory
end
mkdir('Data_examen1', sprintf('pp%d', welke_pp)); %hmake a new subfolder. Here is the warning.
folder = 'Data_examen1';
subfolder = sprintf('pp%d',welke_pp);
pngFileName = sprintf('3Dplot_subject%d_trial%d.png', welke_pp, i_testen);
fullFileName = fullfile([folder '\\' subfolder], pngFileName);
saveas(gcf,fullFileName); %save each figure

 Akzeptierte Antwort

Image Analyst
Image Analyst am 29 Dez. 2014

2 Stimmen

Just wrap your mkdir() in an if statement
if ~exist(folderName, 'dir')
% Folder does not exist so create it.
mkdir(foldername);
end
If it exists already, it won't do this and therefore won't throw an error.

3 Kommentare

For the subfolder, it is a bit harder I think... I tried this:
if ~exist(sprintf('pp%d', welke_pp), 'dir')
mkdir(sprintf('pp%d', welke_pp))
But Matlab doesn't make the new subfolder...
It should if you specify the full path of the folder.
subFolder = sprintf('pp%d', welke_pp);
fullPath = fullfile(someRootFolder, subFolder);
if ~exist(fullPath , 'dir')
% Folder does not exist so create it.
mkdir(fullPath );
end
Your code probably actually did create the folder but in a location you were not expecting and did not look for or in. Do it my way and look at the fullPath value and see if it makes sense. Then use the debugger to see if it actually enters the "if" block.
Sam
Sam am 29 Dez. 2014
Thanks a lot! It works!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Tags

Gefragt:

Sam
am 29 Dez. 2014

Kommentiert:

Sam
am 29 Dez. 2014

Community Treasure Hunt

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

Start Hunting!

Translated by