# Remove a specific dimension

220 views (last 30 days)
Michael on 17 Jul 2014
Commented: Michael on 17 Jul 2014
I have a code that works with an array of 3D points, so the arrays are of size A x B x 3. However, there are times where I only want the first dimension, so the arrays are of size A x B (x 1, but this dimension is left off).
Then I want to sum the arrays along the first dimension (A x B x 3 -> 1 x B x 3). I then convert it to just a B x 3 matrix by using squeeze, which works fine for 3D arrays. But for 2D arrays, squeeze essentially does nothing (A x B (x 1) -> 1 x B (x 1), which squeeze does nothing to).
If there a way to specify to remove the first dimension? (Or force an array to have trailing singleton dimensions?) The first dimension will always be 1 by this point, so I don't have to worry about it. But in the case where I start with an array of size A x B (x 1), I want it to become B x 1 at the end.
[Yes, I know I can just transpose it, but I that's not what is happening mathematically, so I would like to avoid transpose.]
Here's a snippet of my code:
data = rand(5,4,3); % a 5x4x3 array
summed = sum(data); % a 1x4x3 array
squeezed = squeeze(summed); % a 4x3 array
x_result = squeezed(:,1); % a 4x1 array (the result of the x data)
However, if it's run with a "2D array", it fails
data = rand(5,4,1); % a 5x4 array (want a 5x4x1 array!)
summed = sum(data); % a 1x4 array
squeezed = squeeze(summed); % a 1x4 array (nothing happened)
x_result = squeezed(:,1); % a 1x1 array (meaningless)
[MATLAB 2011a on a Mac]

James Tursa on 17 Jul 2014
If you know the first dimension is always a singleton at some point in your calculation, you can use reshape instead of squeeze to force things. E.g.,
z = size(summed);
squeezed = reshape(summed,[z(2:end) 1]);

#### 1 Comment

Michael on 17 Jul 2014
Wow, it's so simple. And it makes sense. Thanks!