Why the squeeze function squeeze 1x3 array to 1x3, but squeeze 1x1x1x3x1 to 3x1?
Show older comments
>> 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 Comments
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
on 17 Dec 2024
Like LENGTH, SQUEEZE is fundamentally unpredictable and best avoided.
Use RESHAPE or PERMUTE or SHIFTDIM instead.
Accepted Answer
More Answers (2)
Walter Roberson
on 17 Dec 2024
1 vote
"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
on 17 Dec 2024
Moved: Walter Roberson
on 17 Dec 2024
0 votes
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.
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!