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

조회 수: 2 (최근 30일)
Anu
Anu 2022년 1월 25일
댓글: Anu 2022년 1월 25일
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.

채택된 답변

DGM
DGM 2022년 1월 25일
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
Anu
Anu 2022년 1월 25일
Thanks so much for the details and your prompt reply, @DGM! I really appreciate it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by