在Matlab中挤压一些Singleton维数

时间:2014-05-16 19:45:18

标签: arrays matlab matrix multidimensional-array

如何在Matlab中仅挤压矩阵的单个维度子集?挤压功能将它们全部删除。

我将索引保存在名为“dims”的向量中的那些维度。

2 个答案:

答案 0 :(得分:4)

在Matlab中,没有拖尾单身维度。 n * m * 1矩阵自动为n * m矩阵。知道了这一点,您的问题就可以解决,从而排列您不希望结束的维度:

X=ones(2,1,2,1,2,1,2,1,2,1)
%dimensions you want to keep in any case
dims=[2:4];
%Notice, S is [2,1,2,1,2,1,2,1,2], last dimension already "gone"
S=size(X)
%keep if size>1
dimensions_to_keep=S>1
%and keep if in "dims" list
dimensions_to_keep(dims)=1
%now permute dimensions you don't want to the end
Y=permute(X,[find(dimensions_to_keep),find(~dimensions_to_keep)])

答案 1 :(得分:3)

<强>代码

%// Input matrix is assumed as A
sz = size(A)
t2 = sz~=1
t2(dims)=1
out = reshape(A,sz(t2)) %// out is the desired output

如果您对密集代码感到疯狂,可以试试这个 -

sz = size(A)
out = reshape(A,sz(sort([dims find(sz~=1)])))