Change names of files in a folder

10 次查看(过去 30 天)
Hi I am trying to change all the file names in a folder I have of .tif images. I want to use the number of tif images in the file to be apart of the new save name.
INDIV = 'folder_path'; %
filenames_INDIV = dir(fullfile(INDIV, '*.tif')); % <-- 126x1 struct
original_images_indv = numel(filenames_INDIV); % <-- 126
for g = 1 : filenames_INDIV
for h = 1 : original_images_indv
[~, f] = fileparts(filenames_INDIV(h).name);
% write the rename file
rf = strcat(f,'SAM%03d', h) ;
% rename the file
movefile(filenames_INDIV(h).name, rf);
end
end
But I end up getting
Undefined function 'colon' for input arguments of type 'struct' for the first for statement
  2 个评论
Adam
Adam 2019-10-22
Well, yes, as your own comments tell you filenames_INDIV is a (126x1) struct so using it as
1:filenames_INDIV
clearly won't work. I guess you could use
1:numel( filenames_INDIV )
although it isn't obvious to me what the outer loop does anyway since g is never referenced.
no zoop
no zoop 2019-10-22
I'm not sure why I left the outer loop in the first place is either. I think I was trying to follow the format I had earlier in the code.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2019-10-22
编辑:Guillaume 2019-10-22
In some ways your code is very well written with variable names that are descriptive and the correct functions used. In some other ways, it looks like it's been written by somebody who's just throwing random code at the wall and see what works. Puzzling!
Case in point, the line that gives you the error. You're iterating from 1 to ... a structure!? Matlab rightly tells you that it doesn't know how to do that, sorry, the : operator has no meaning when a structure is passed as an index. it's not even clear what the whole line is meant to do. The h loop on the following line would do the desired job on its own.
Then we have the strcat(f,'SAM%03d', h) which is again nonsense. It appears to be a strcat operation and sprintf operation all in one. It certainly won't produce the result required. Plus the new file name doesn't have an extension anymore.
And finally, we have the movefile which now longer use the folder path so will fail anyway since it will attempt to rename files in the current folder instead of the INDIV folder.
I suspect the code should be:
INDIV = 'folder_path';
filenames_INDIV = dir(fullfile(INDIV, '*.tif'));
for filenum = 1 : numel(filenames_INDIV);
[~, basename] = fileparts(filenames_INDIV(filenum).name);
newname = sprintf('%s_SAM%03d.tif', basename, filenum);
movefile(fullfile(INDIV, filenames_INDIV(filenum).name), fullfile(INDIV, newname));
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by