필터 지우기
필터 지우기

Change names of files in a folder

조회 수: 12 (최근 30일)
no zoop
no zoop 2019년 10월 22일
댓글: no zoop 2019년 10월 22일
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