MATLAB: How to solve this batch process error: “Error using movefile The process cannot access the file because it is being used by another process”

batch processimage batch processmovefilerename filesequential file renaming

I'm trying to run this code to batch process some image stacks. I get an error code in the end, when I try to rename each 'test.tif' file I get at the end of the second for loop using a movefile function. I want to rename them as test_1.tif, test_2.tif as they are being processed within the first for loop. When I run the code using the Image-BatchProcess App, I get an error message "Error using movefile The process cannot access the file because it is being used by another process". I am not able to figure out which process is still using the 'test.tif' file that I generate at the end of the second for loop. I'd appreciate any thoughts/help here.
Here is my code:
Image_folder= uigetdir;
Diff_stack_folder=uigetdir;
Image_Dir=dir([Image_folder '/*.tif']);
total_images=size(Image_Dir, 1);
for n= 1: total_images
filename= Image_Dir.name;
fid=fopen(filename);
info = imfinfo(filename);
num_images = numel(info);
for k = 1:num_images - 1
A = imread(filename, k, 'Info', info);
B = imread(filename, k + 1, 'Info', info);
Q = A - B;
imshow(Q, []);
imwrite(Q,'test.tif','WriteMode', 'append')
end
[~, f,ext] = fileparts(Image_Dir(n).name);
rename = sprintf('test_%d.tif',n);
movefile(Image_Dir(n).name, rename);
end

Best Answer

You have the file open with fid=fopen(filename)
run fclose() before you run movefile().