Controlling MATLAB memory use is a bit of a black art. There are general guidelines that can be followed, but no hard and fast rules that will work in every case. Here are some soft rules:
PET = getimages(h,8,1:21,PET);will re-use the memory assigned to the matrix PET, and will not allocate new memory for the returned images. This eliminates the fragmentation associated with reloading a set of images.
PET = PET .* 5;will cause fragmentation since the matrix PET will be copied. However, the instruction:
rescale (PET,5);has the same effect, but without causing fragmentation.
Fake_PET = zeros(128,128);This will initialize the matrix to the correct size, and fill it with zeros. Then, when you fill the matrix in with your values, it will not be copied, and memory fragmentation will not occur.
h=openimage('/local/matlab/toolbox/emma/examples/yates_19445.mnc'); h2 = newimage('new.mnc',[0 15], ... '/local/matlab/toolbox/emma/examples/yates_19445.mnc'); ftimes = getimageinfo (h,'MidFrameTimes'); img = zeros (16384,1); for j=1:15 PET = getimages(h,j,1:21); img = ntrapz(ftimes,PET')'; putimages(h2,img,j); end; closeimage(h); closeimage(h2);This brute force technique violates several of the above guidelines. It does not re-use memory when loading images from the MINC file. It transposes PET, which causes PET to be copied. It then transposes the result from ntrapz, which causes this result to be copied.
A better approach is to load the images for one slice, take the data line by line, and then re-assemble this into a final image. The following piece of MATLAB code has the same final result as the above, but uses much less memory (approximately 4 Megabytes).
h=openimage('/local/matlab/toolbox/emma/examples/yates_19445.mnc'); h2 = newimage('new.mnc',[0 15], ... '/local/matlab/toolbox/emma/examples/yates_19445.mnc'); ftimes = getimageinfo (h,'MidFrameTimes'); img = zeros (16384,1); for j=1:15 PET = getimages(h,j,1:21,PET); for i=1:128:16257; line = PET(i:i+127,:); img (i:i+127) = ntrapz(ftimes, line')'; end; putimages(h2,img,j); end; closeimage(h); closeimage(h2);