Change names of files in a folder

10 views (last 30 days)
no zoop
no zoop on 22 Oct 2019
Commented: no zoop on 22 Oct 2019
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 Comments
Adam
Adam on 22 Oct 2019
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 on 22 Oct 2019
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.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 22 Oct 2019
Edited: Guillaume on 22 Oct 2019
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

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!