Looping through a 3D array to find the mean and standard deviation

坚强是说给别人听的谎言 提交于 2019-12-11 05:28:37

问题


Ok so I have an array <134x106x108>. What I'm trying to do is loop through this array and store the average/standard deviation into another array. So basically there will be 134 <106x108 doubles> that will be in this meanArray and sdArray.

 %dayv=<134x106x108>
 sdArray=zeros(1,106,108);
 meanArray=zeros(1,106,108);
for i=1:size(dayv,1)
    %store means/standard deviation into an array
    meanArray(i,:,:) = squeeze(mean(dayv(i,:,:)));
    sdArray(i,:,:) = squeeze(std(dayv(i,:,:)));
end

回答1:


If you want each of your means to be the average of an entire 106x108 matrix then one easy solution is to reshape your 3d matrix into a 2d matrix using,

dayv2 = reshape(dayv,[134 106*108]);

Now each of those 106x108 matrices is a row vector in your new matrix.

Then

meanArray = mean(dayv2,2); % Get mean of each row
stdArray  = std(dayv2,0,2);% Std of each row



回答2:


You should not need to use a loop to solve this problem. The matlab built-in functions mean and std are capable of computing along individual dimensions of a matrix:

meanArray = squeeze(mean(dayv, 1));
sdArray = squeeze(std(dayv, [], 1));

The above code will average along the first dimension, and produce a meanArray and sdArray which are 106x108, as you initialize in your code. If, on the other hand, you want meanArray and sdArray to be single-dimensional vectors of length 134 (as implied by your loop), you would do

meanArray = mean( mean(dayv, 3), 2 );
sdArray = squeeze(std( reshape( dayv,  134, [] ), [], 2 ));

where reshape reorganizes your matrix so that it is 134x(106*108), so that std can act on it properly.

You can compare the above approach with the for-loop based code:

for i=1:size(dayv,1)
  slice = squeeze(dayv(i,:,:));
  meanArray(i) = mean(slice(:));
  sdArray(i) = std(slice(:));
end


来源:https://stackoverflow.com/questions/13613557/looping-through-a-3d-array-to-find-the-mean-and-standard-deviation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!