MATLAB Answers


reshape and sum multi-dimensional matrix

Asked by ehsan
on 18 May 2018 at 10:38
Latest activity Commented on by ehsan
on 18 May 2018 at 11:23

Hi, I have a 20-by-30-by-40 matrix. I would like to sum each two page of the third dimension. In the end, I need to have a 20-by-30-by-20 matrix.

I appreciate if you could help me.


Sign in to comment.

2 Answers

Answer by Stephen Cobeldick on 18 May 2018 at 10:49
Edited by Stephen Cobeldick on 18 May 2018 at 10:50
 Accepted Answer

Where A is your array:

A(:,:,1:2:end) + A(:,:,2:2:end)


Sign in to comment.

Answer by Sammit Jain on 18 May 2018 at 10:58

Hi, I think what you're trying to do can be accomplished without reshaping the multi-dimensional matrix.

% Initializing 20x30x40 matrix of random elements
X = rand(20,30,40);
% Splitting the matrix into 2 sets based on the alternating third dimension
% The two sets are of dimensions 20x30x20 each.
% Taking out odd elements of third dimension
setA = X(:,:,1:2:40);
% Taking out even elements of third dimension
setB = X(:,:,2:2:40)
% Adding the two sets A and B
result = setA+setB;

The key here is splitting the main matrix into two 'pages' that you actually want to add.

  1 Comment

Thanks for your explanation Sammit. Actually, your answer is right as the Stephen's answer.

Sign in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today