MATLAB: How to make directories within directories within directories

directoryMATLABmkdirpath

Hi,
The first loop 'for i=1..' creates 3 directories, '1,2,3'. The second loop, 'for n=1:..', then creates two directories inside each of them called 'a' and 'b'. The code is successful thus far. The final loop (list3) attempts to create two further directories 'q' and 'r' within 'a' and 'b'. This loop produces another a,b containing q,r, which is fine, but at the same level as 1,2,3 which is not. So I obtain mainfolder\(1&2&3)\(a&b) + mainfolder\(a&b)\(q+r), rather than the required mainfolder\(1&2&3)\(a&b)\(q+r). I was attempting to use mkdir as in the example: mkdir(Parentfolder, foldername) which creates the foldername within Parentfolder. Thanks in advance! Sorry for the long winded explanation and awkward notation
function testforum();
list1=["1","2","3"]
list2=["a","b"]
list3=["q","r"]
for i=1:length(list1)
x=list1(i)
mkdir(sprintf('%s',x))
for n=1:length(list2)
y=list2(n)
mkdir (sprintf('%s',x),sprintf('%s',y))
for p=1:length(list3)
z=list3(p)
mkdir (sprintf('%s',y),sprintf('%s',z))
end
end
end
end

Best Answer

Use absolute paths for the folders. You cannot create a subfolder using the mkdir(parent, sub) notation, if parent is not found. Example:
base = 'D:\Temp'; % Assumed to be existing
cd(base);
mkdir('A'); % C:\Temp\A created
mkdir('A', 'B'); % C:\Temp\A\B created, because 'A' is found in current directory
mkdir('B', 'C'); % This creates C:\Temp\B\C, not C:\Temp\A\B\C
mkdir('A\B', 'C'); % This creates C:\Temp\A\B\C
Much easier:
mkdir(fullfile(base, 'A', 'B', 'C'))
Use full path names to avoid any troubles. The notation mkdir(parent, sub) was needed in Matlab R5.3, but after 20 years I suggest to use the modern power of mkdir to create a complete folder tree at once.
A fixed version of your code:
base = 'D:\Temp'; % Set as needed
list1 = {'1', '2', '3'}
list2 = {'a', 'b'}
list3 = {'q', 'r'}
for i = 1:length(list1)
x = list1{i}
for n = 1:length(list2)
y = list2{n}
for p=1:length(list3)
z = list3{p}
mkdir(fullfile(base, x, y, z));
end
end
end