# How to have a sum of 2d fields in a 3d matrix so the time dimension remains?

18 views (last 30 days)
Mikolaj Jankowski on 28 Feb 2019
Commented: Mikolaj Jankowski on 28 Feb 2019
Hello,
I have the following problem:
I have a 3D matrix with dimensions seen below and I am trying to get mean values of fields on first two dimensions,
while keeping the last dimension resolution, so the final matrix would be a 31 length vector. I have tried as seen below,
but that failed for the moment.
I would greatly appreciate a suggestion on how to do that correctly
% ice_sum_1st_aug is a matrix 480x30x31 - trying to get sum of values on 480x30 bits against time
% the needed result would be a vector of 31 points in lenght
for k=1:31
icesum_1st_aug(k)=sum(ice_1st_august(:,:,k));
end

Walter Roberson on 28 Feb 2019
icesum_1st_aug = sum(sum(ice_1st_august,1),2);
If you have R2018b or later then
icesum_1st_aug = sum(ice_1st_august, [1 2]);
If you really want to loop,
nk = size(ice_1st_august,3);
icesum_1st_aug = zeros(1,1,nk);
for k = 1 : nk
icesum_1st_aug(1,1,k) = sum(reshape(ice_1st_august(:,:,k),[],1));
end
Mikolaj Jankowski on 28 Feb 2019
Thank you, it worked, I found out how to apply it and get the result I need :)

Steven Lord on 28 Feb 2019
If you're using release R2018b or later, both sum and mean (your code used sum but your description of your goal indicated you're looking for the mean) accept a vector as the dimension input argument to operate over multiple dimensions simultaneously.
A = randi(10, [4, 5, 3]);
meanOfEachPage = mean(A, [1 2]);
You can check this, for example for the first page of A:
firstPage = A(:, :, 1);
meanOfFirstPage = mean(firstPage(:));
meanOfFirstPage - meanOfEachPage(1)
See the Release Notes for a list of the functions that support this functionality.