What does squeeze() do in MATLAB?
269 次查看(过去 30 天)
显示 更早的评论
Hi All,
Can anyone tell me about the use of squeeze() function in a MATLAB program?
Thanks in advance!
Swati
2 个评论
采纳的回答
John D'Errico
2020-11-19
编辑:John D'Errico
2020-11-19
Squeeze is a useful tool to help compress dimensions of a multidimensional array when you have performed some operations. Let me give you a couple of examples as to why it is useful.
Suppose we have a 3 dimensional array.
A = rand(2,3,4);
size(A)
Now suppose we wanted to extract some plane of the array? Thus to form A(1,:,:)? This should be 2-dimensional thing, right?
A(1,:,:)
Hmm. It is not. At least, that does not look like a 2-dimensional array. In fact, MATLAB thinks it is 3-d still.
size(A(1,:,:))
Or, suppose we wanted to form the mean, on the SECOND dimension of A?
mean(A,2)
size(mean(A,2))
So in both cases, I started with a 3-dimensional array, operated on it in a way that logically SHOULD have produced a 2-d array.
Squeeze fixes the problem, by dropping out those spurious singleton dimensions. That is,
squeeze(A(1,:,:))
size(squeeze(A(1,:,:)))
squeeze(mean(A,2))
size(squeeze(mean(A,2)))
This allows you to get the result you wanted, in the shape you would have expected.
There is one small caveat to remember. All arrays in MATLAB are treated as if they have infinitely many trailing singleton dimensions. So a scalar is actually an array of size 1x1x1x1x1x1x1x1..., and a vector an array of size Nx1x1x1x1..., or 1xNx1x1x1x1... MATLAB never reports those trailing singleton dimensions however, at least not beyond the second dimension. (This is probably a consequence of requiring backwards compatibility all the way back to version 1 when possible, when MATLAB did not have multidimensional arrays at all.) So we see:
V = 1:3;
size(V)
size(V.')
S = 2;
size(S)
Logically, if we apply squeeze to a scalar, we still have a scalar.
size(squeeze(S))
size(squeeze(V.'))
size(squeeze(V))
So the only thing to remember is that squeeze does not convert a 1x3 vector into a 3x1 vector. (In my eyes, I disagree with the design of squeeze in that respect, but I did not write the code.)
W = A(1,1,:)
So W is a vector, but stored in a 3-dimensional form. It has size 1x1x4.
size(W)
size(squeeze(W))
So be careful when squeezing vectors, as it is not always perfectly consistent. At least not in my eyes.
Having read all of that, you should now be a master of the squeeze.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Particle Swarm 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!