问题
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