Using movefile can help you. Below is an example script. Please create an empty folder and set the folder as a current folder of MATLAB.
You can run the script below to learn how finding folder names and changing them works.
basepath = pwd;
%% Creating environment
for i_main = 1:100
% creating 100 main folders
mkdir("main" + i_main)
cd(fullfile(basepath, "main"+i_main))
% creating a subfolder named "subfolder1"
mkdir("subfolder1")
% creating 20 files inside subfolder1
cd(fullfile(basepath, "main"+i_main,"subfolder1"))
for i_file = 1:20
fid = fopen("file"+i_file+".txt", "w");
fprintf(fid, "foo");
fclose(fid);
end
cd(basepath)
end
%% find a subfolder and change its name
cd(basepath)
D = dir;
% removing current path or previous path
idx2del = strcmp(string({D.name}), ".") | strcmp(string({D.name}), "..");
D(idx2del) = [];
names_mainfolder = {D.name};
for i_main = 1:length(names_mainfolder)
cd(fullfile(basepath, names_mainfolder{i_main}))
% finding the name of subfolder
D = dir;
idx2del = strcmp(string({D.name}), ".") | strcmp(string({D.name}), "..");
D(idx2del) = [];
% changing the name of subfolder into the main folder
movefile(D.name, names_mainfolder{i_main})
end
