Why the squeeze function squeeze 1x3 array to 1x3, but squeeze 1x1x1x3x1 to 3x1?

조회 수: 7 (최근 30일)
>> size(squeeze(rand(1,1,1,3,1,1,1)))
ans =
3 1
>> size(squeeze(rand(1,1,3,1,1,1)))
ans =
3 1
>> size(squeeze(rand(1,3,1,1,1))) % this is the unexpected results. Why not 3 x 1
ans =
1 3
>> size(squeeze(rand(3,1,1,1)))
ans =
3 1
  댓글 수: 2
Matt J
Matt J 2024년 12월 17일
편집: Matt J 2024년 12월 17일
Even if it did as you expect, it is rarely safe/robust to use squeeze(), because you rarely know when the leading dimension you want will reduce during some computation to a singleton.
Similar to eval(), squeeze() is something one should strive to avoid. Use A(:) or shiftdim() instead.
Stephen23
Stephen23 2024년 12월 17일
Like LENGTH, SQUEEZE is fundamentally unpredictable and best avoided.
Use RESHAPE or PERMUTE or SHIFTDIM instead.

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

채택된 답변

Steven Lord
Steven Lord 2024년 12월 17일
If I recall correctly (this was before my time at MathWorks started) squeeze was introduced when we introduced arrays with more than 2 dimensions in MATLAB. Arrays in MATLAB have to have at least two dimensions (the size function with 1 input and 1 output is generally expected to return a vector with two or more elements, I think strange things can happen if you have a class whose overloaded size method returns a scalar or empty) and so squeezing out singleton dimensions that would leave two or more dimensions is reasonable. But if you squeeze a 1-by-3 vector, do you want it to become a 3-by-1 vector?
This edge case is documented on the squeeze documentation page, BTW. "If A is a row vector, column vector, scalar, or an array with no dimensions of length 1, then squeeze returns the input A." Since the trailing singleton dimensions are dropped when rand is determining what size output to return, rand(1,3,1,1,1) is a row vector and so squeeze returns it unchanged.
sz = size(rand(1,3,1,1,1))
sz = 1×2
1 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

추가 답변 (2개)

Walter Roberson
Walter Roberson 2024년 12월 17일
"because"
It was a design choice for the function. It leaves the array alone if ndims is 2 and otherwise removes all of the singular dimensions.

Tony
Tony 2024년 12월 17일
이동: Walter Roberson 2024년 12월 17일
There appears to be a heuristic involved that when there is only one non-singleton dimension, if it looks like the expansion of a row vector (the second dimensions is the non-singleton one), then squeeze the input into a row vector. Otherwise, squeeze into a column vector. Which from usage perspective, I agree with and believe is the more useful choice. When the non-singleton dimension is third or higher, then there's ambiguity about the more "useful" choice, and so the algorithm defaults to just column vector.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by