MATLAB: Mixing string name and number,is the commmand correct?

deletename

Hi All
Since I just dont remember and dont know how to search for this question
would like to know
for naming the file as :
for i=1:100
delete('filename'+num2str(i))
end
is it correct ?

Best Answer

I'd recommend you follow the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F because your method is not very robust. I prefer sprintf(). If you're not going to use, or can't use, dir() to get a listing of what files are there, then at least you should use exist() so you don't throw an exception that aborts your loop when the file is not found. That is what people do when they write robust code.
for k = 1 : 100 % Use k, not i (the imaginary variable)
baseFileName = sprintf('filename%d', k);
% Prepend the folder where the files live.
% If it's the current folder, then you can use folder = pwd.
fullFileName = fullfile(folder, baseFileName);
if exist(fullFileName, 'file')
% If the file exists, delete it.
delete(fullFileName);
end
end
but again, see the FAQ for better code examples than that.