How do I rename the .mat files in a for loop?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
DGM
le 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.
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur File Operations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!