Reputation: 25
I have an I x K x V array, where V = S x R, ie, the third dimension has "S" observation for "R" different categories. I would like to end up with an I x K x S that has, in the third dimension, the sum across R within each S.
e,g: I = 3, K = 3, S=2 and R=2, I want to end up with a matrix C that is 3x3x2 that sums the third dimension in the following way.
A = [5 7 8; 0 1 9;4 3 6];
A(:,:,2)=[1 0 4; 3 5 6;9 8 7]
A(:,:,3)=[3 2 1 ; 4 5 6; 3 4 5]
A(:,:,4)=[1 2 3 ; 3 4 5; 5 6 7]
C=A(:,:,1)+A(:,:,2)
C2=A(:,:,3)+A(:,:,4)
C(:,:,2)=C2
I cannot do this manually b/c R and S are very large in my "real" case.
Thanks!
Upvotes: 1
Views: 2513
Reputation: 112659
Separate the S and R dimensions with reshape
, and then sum
across the third dimension, which is S:
I = 3; K = 3; S = 2; R = 2;
C = squeeze(sum(reshape(A,[I K S R]),3));
If you want to sum across R, that's the fourth dimension:
C = sum(reshape(A,[I K S R]),4);
Upvotes: 1