MATLAB: How to save files using for loop

Image Processing Toolbox

Hello. So I am trying to save an image using a for loop after I had cropped the image. Though how can I avoid copying and pasting the same code. I want to produce a for loop that will give me the same result as this:
...
cell1= imcrop(I3,stats(1).BoundingBox);
imwrite(cell1,'cell1.tif');
cell2= imcrop(I3,stats(2).BoundingBox);
imwrite(cell2,'cell2.tif');
...
I tried using a for loop but then I wasn't able to change the "i" value in the saved file name. Thank you!

Best Answer

Try this:
for k = 1:10
img= imcrop(I3,stats(k).BoundingBox);
imwrite(img,sprintf('cell%d.tif',k));
end
Note how I use the loop variable k to increment both the indexing into the variable stats and also to generate a new filename (using sprintf) with each iteration of the loop.