Why does squeeze transpose my matrices without my permission and how to stop it?
7 次查看(过去 30 天)
显示 更早的评论
I have tensors of the following size 1 x 1 x D x M. I'd like to squeeze it such that we always have a matrix of size D x M. The code that should do it is:
X = zeros(1,1,D,M);
X = squeeze(X); % (D x M)
However, notice that if the special case where D = 1 then we get the *wrong* behaviour of squeeze:
D = 1;
X = zeros(1,1,D,M);
X = squeeze(X); % (M x 1) = (M x D)
Instead of the desired/expected 1 x M = D x M.
I can easily just write an if code where if D=1 then transpose else do something else, but it seems super hacky because if squeeze has that unexpected weird behaviour who knows what other strange thing it might do. Is there no way to just remove the 1's without squeeze doing transposing for me for any numbers?
0 个评论
回答(2 个)
the cyclist
2016-6-17
编辑:the cyclist
2016-6-17
I think you will find that squeeze's behavior, while surprising to you, is exactly as documented. Why would you expect it not to squeeze out the D=1 dimension?
I'm sympathetic, though. My recommendation is to use the permute command to rearrange the dimensions (which is what you actually want).
7 个评论
Walter Roberson
2016-6-17
"B = squeeze(A) returns an array B with the same elements as A, but with all singleton dimensions removed. A singleton dimension is any dimension for which size(A,dim) = 1"
When your D is 1, all three leading dimensions are singleton, and the documentation does say it removes all singleton dimensions
John D'Errico
2016-6-17
编辑:John D'Errico
2016-6-17
A 1x1xm array is NOT a row OR a column vector. So, while squeeze does not touch row or column vectors, it does work on arrays.
Kelly Kearney
2016-6-17
You could set up a function that uses permute but allows for unlimited dimensions:
mysqueeze = @(x) permute(x, [3:ndims(x) 1 2])
>> size(mysqueeze(rand(1,1,2,3)))
ans =
2 3
>> size(mysqueeze(rand(1,1,1,3)))
ans =
1 3
size(mysqueeze(rand(1,1,2,3,4)))
ans =
2 3 4
4 个评论
Kelly Kearney
2016-6-20
I guess I'm not entirely clear on what your criteria is for keeping vs dropping a particular dimension. How is the function supposed to know which dimensions should remain, even if they are singleton? Will there always be two non-singleton dimensions?
另请参阅
类别
在 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!