Remove a specific dimension

조회 수: 197 (최근 30일)
Michael
Michael 2014년 7월 17일
댓글: Michael 2014년 7월 17일
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
James Tursa 2014년 7월 17일
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
Michael
Michael 2014년 7월 17일
Wow, it's so simple. And it makes sense. Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by