MATLAB: Using a for loop to create a structure of images

for loopframe averageimage processingImage Processing ToolboxMATLAB

I'm using matlab to control a microscope camera. I set up a script to grab 8 frames and average them, shown partially below. (The mmc lines are java commands that let MATLAB communicate via Java to the camera and other microscope parts via the micromanager API):
xpix = mmc.getImageWidth;
ypix = mmc.getImageHeight;
mmc.snapImage();
im.im1 = mmc.getImage();
im.im1 = reshape(uint16(im.im1), xpix, ypix);
mmc.snapImage();
im.im2 = mmc.getImage();
im.im2 = reshape(uint16(im.im2), xpix, ypix);
...
mmc.snapImage();
im.im8 = mmc.getImage();
im.im8 = reshape(uint16(im.im8), xpix, ypix);
avim = (im.im1 + im.im2 ... + im.im8)/8;
So, is there an easier way I could set this up using a for loop? I don't know how to tell it to name a variable or parts of a structure sequentially. It would be nice if there were a variable n, that the use could input to tell it how many frames to average, either in the first line of the script (n=4) or as a variable when i make it into a function. I am not profient in MATLAB so my efforts to write a for loop so far have not worked.

Best Answer

Why does it need to be reshaped? Anyway, what's wrong with this:
sumImage = zeros(ypix, xpix);
for frameNumber = 1 : 8
mmc.snapImage();
sumImage = sumImage + mmc.getImage();
pause(0.5); % If you want a time between grabbed frames.
end
meanImage = sumImage / 8;