MATLAB: Mean of many changing “for loop” 3D matrices

3d matrices

Hi,
I have 200 3D matrices with same dimensions. I'd like to create one 3d matrix that would contain mean of my 200 matrices by elements → (1,1,1) mean of 200 positions in my 3D matrices and so on …
Here's my code:
for tt = 1:200;
M = ... (tt) loads the 3D data
end
mean()
Can you help me please?
Thanks.

Best Answer

Well, you could do that (store in a 4D array, that is) but that requires memory for all 200 at once and there's no need when computing a mean to have all the data at once...just accumulate the totals and then divide after the loop is finished...
M = spm_read_vols(spm_vol(files(1).name)); % read the first into accumulator array
for tt = 2:200
M=M+spm_read_vols(spm_vol(files(tt).name)); % accumulate the total
end
M=M/200; % average