Like Walter said, you're not changing img inside your loop so it's always the same. As an extra precaution against overwriting, use the exist() function
if exist(filename, 'file')
promptMessage = sprintf('%s already exists.\nDo you want to overwrite it', filename);
titleBarCaption = 'Overwrite?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Yes', 'No', 'Yes');
if strcmpi(buttonText, 'Yes')
imwrite(img.cdata,filename);
end
else
imwrite(img.cdata,filename);
end
Note that filename is already the full path so you don't need to send it into fullfile again when you call imwrite().
Best Answer