MATLAB: Renaming Files based on a Folder Name in Sequence

filenamefoldernameincrementloopMATLAB and Simulink Student Suite

Hi, I am trying to do the following: I have folders participant 1, participant 2, etc. I want to name the files xxxx-folder name. Each file name is different but begins with 0001_. How can I do this in a loop (for multiple folders)?

Best Answer

Thank you for the clarification. Then, the program would be something like this.
s = dir('./participant*/*.*');
prevDir = '';
for kk = 1:numel(s)
if ~s(kk).isdir
oldName = s(kk).name;
[~,~,ext] = fileparts(oldName);
[~,currDir] = fileparts(s(kk).folder);
if ~strcmp(s(kk).folder,prevDir)
pref = 1;
prevDir = s(kk).folder;
else
pref = pref + 1;
end
newName = sprintf('%04d_%s%s',pref,currDir,ext);
movefile(fullfile(s(kk).folder,oldName),fullfile(s(kk).folder,newName));
end
end