Tulkkas
Tulkkas

Reputation: 1013

Summing over specific dimension of a 3D matrix in Matlab

I have a 3D matrix in Matlab of size NxMxD and i need to sum over a specific dimension:

x = rand(5,3,2);
sum1 = sum(x,1);
sum2 = sum(x,2);
sum3 = sum(x,3);

I would obviously expect in the 3 case that the result would be either a 2D matrix or a 3D matrix with 1 dimension of length 1. This is unfortunately not the case.

sum1 and sum2 are 3D matrix with the dimension over which the sum is done of length 1 but sum3 is a 2D matrix.

I would like to be able to get sum1 and sum2 as 2D matrix in the similar way sum3 is being computed. Is that possible to do using sum only or the only way is to further use for example the squeeze() function )

Upvotes: 0

Views: 108

Answers (1)

Nicky Mattsson
Nicky Mattsson

Reputation: 3052

As @Tommaso says, the third output is 5x3x1, though when you ask for its size MATLAB cuts of trailing ones.

MATLAB, cannot automatically do this in other places, because this would change the matrix/tensor, remember that MATLAB is “primarily” for matrices.

A 1xn vector is not the same as an nx1 vector, when performing matrix operations.

Tl;dr, you will have to use squeeze or reshape

Upvotes: 3

Related Questions