MATLAB: Dir() function not working

MATLAB

Hello,
I'm trying to rename some files using the code below. It works if I list the file names at the beginning but there are many files in the folder so I wanted to use the dir()function but it won't work for some reason. Would anybody know why?
Thanks
Working code:
files = {'RW.a_process',...
'Copy of RW.a_process',...
'Copy (2) of RW.a_process',...
'Copy (1000) of RW.a_process'}
for k = 1 : length(files)
oldFileName = files{k}
leftParenthesisLocation = strfind(oldFileName, 'Copy (');
if leftParenthesisLocation >= 1
% Handle cases of Copy (nnn) of RW.a_process
rightParenthesisLocation = strfind(oldFileName(leftParenthesisLocation:end), ')');
if rightParenthesisLocation > 1
strNumber = oldFileName(leftParenthesisLocation+6:rightParenthesisLocation-1)
% Get name to the right of the right parenthesis.

newFileName = oldFileName(rightParenthesisLocation+5:end);
[folder, baseFileName, ext] = fileparts(newFileName);
newFileName = sprintf('%s%s%s', baseFileName, strNumber, ext);
fprintf('New Filename = %s\n', newFileName); % Print blank line.

end
Not working code:
files = dir('*.a_process');
for k = 1 : length(files)
oldFileName = files{k}
leftParenthesisLocation = strfind(oldFileName, 'Copy (');
if leftParenthesisLocation >= 1
% Handle cases of Copy (nnn) of RW.a_cycle
rightParenthesisLocation = strfind(oldFileName(leftParenthesisLocation:end), ')');
if rightParenthesisLocation > 1
strNumber = oldFileName(leftParenthesisLocation+6:rightParenthesisLocation-1)
% Get name to the right of the right parenthesis.
newFileName = oldFileName(rightParenthesisLocation+5:end);
[folder, baseFileName, ext] = fileparts(newFileName);
newFileName = sprintf('%s%s%s', baseFileName, strNumber, ext);
fprintf('New Filename = %s\n', newFileName); % Print blank line.
movefile(oldFileName, newFileName)
end

Best Answer

You need to use
oldFileName = files(k).name
see