Why the squeeze function squeeze 1x3 array to 1x3, but squeeze 1x1x1x3x1 to 3x1?
40 次查看(过去 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
2024-12-17,16:14
编辑:Matt J
2024-12-17,16:16
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
2024-12-17,16:32
Like LENGTH, SQUEEZE is fundamentally unpredictable and best avoided.
Use RESHAPE or PERMUTE or SHIFTDIM instead.
采纳的回答
Steven Lord
2024-12-17,15:37
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))
0 个评论
更多回答(2 个)
Walter Roberson
2024-12-17,7:58
"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.
0 个评论
Tony
2024-12-17,7:50
移动:Walter Roberson
2024-12-17,7:54
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!