1

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!

1
  • You say you want to "sum across R" (fourth dimension), but then you say you want a matrix "that sums the third dimension". I consider both cases in my solution Commented Nov 24, 2013 at 3:05

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I am sorry if I lead to confusion, A was meant to be constructed with only three dimensions, so your first answer (reshaping first) is what I needed. Works beautifully, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.