How do I rename the .mat files in a for loop?

13 views (last 30 days)
I have 1000 .mat files. for example, angle1.mat, angle2.mat, angle3.mat.....angle1000.mat. I want to rename these respective files as angle501.mat, angle502.mat, angle503.mat.....angle1500.mat. Something like I wanted to add 500 to the number.
S = dir('*.mat');
fileNames = {S.name};
for k=1:length(fileNames)
H=fileNames{k};
movefile(H, sprintf('angle%d.mat', k));
end
I think we need to change something inside the sprintf, but don't know how to do it. May I know how to solve the issue?
Thanks.

Accepted Answer

DGM
DGM on 25 Jan 2022
Since your filenames all have variable-length numbers in them, they won't sort like you expect. If you've already run this code, your files have probably been renamed out of order.
Consider that you have the files
test_1.mat
test_2.mat
test_10.mat
test_20.mat
test_100.mat
test_200.mat
Using dir() will return the filenames in this order:
test_1.mat
test_10.mat
test_100.mat
test_2.mat
test_20.mat
test_200.mat
and then you'll rename them in the wrong order.
There are ways to deal with this. You could use this tool to sort the filenames:
S = dir('angle*.mat'); % use a more restrictive expression
fileNames = natsortfiles({S.name}); % sort the names
for k=1:length(fileNames)
H = fileNames{k};
movefile(H, sprintf('angle_%04d.mat', k+500));
end
Note that this simply assumes that the file names contain the numbers matching the vector k.
Alternatively, you could extract the numbers from the filenames and add to them.
S = dir('angle*.mat'); % use a more restrictive expression
fileNames = {S.name}; % unsorted names
filenums = regexp(fileNames,'(?<=[^\d])\d+(?=\.)','match');
filenums = str2double(vertcat(filenums{:}));
for k=1:length(fileNames)
H = fileNames{k};
movefile(H, sprintf('angle_%04d.mat',filenums(k)+500));
end
Note that in both cases, the output filenames are zero-padded to a fixed length. This makes them easily sortable.
  1 Comment
Anu
Anu on 25 Jan 2022
Thanks so much for the details and your prompt reply, @DGM! I really appreciate it.

Sign in to comment.

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!