在 Matlab 中压缩一些单例维度

问题描述 投票:0回答:3

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

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

arrays matlab matrix multidimensional-array
3个回答
4
投票

代码

%// 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)])))

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)])

0
投票

@Divakar 的回答

dims
视为“保留什么”。对于“要删除什么”,下面基本上将一个转换为另一个并粘贴到该答案中:

sz = size(A);
keepdims = 1:numel(sz);
keepdims = keepdims(~arrayfun(@(i)ismember(i, dims_user), keepdims));
no_squeeze = sz~=1;
no_squeeze(keepdims) = 1;
out = reshape(A, sz(no_squeeze));

示例

size(out)
A = randn(1, 1, 3, 1, 4)

dims_user = 1;    % 1     3     1     4        | drops dim1
dims_user = 2;    % 1     3     1     4        | drops dim2 (same effect)
dims_user = 3;    % 1     1     3     1     4  | ignores drop request
dims_user = 4;    % 1     1     3     4        | drops dim 4
dims_user = 1:2;  % 3     1     4              | drops dims 1, 2
dims_user = 1:3;  % 3     1     4              | drops dims 1, 2, ignores 3
dims_user = 1:5;  % 3     4                    | == `squeeze(A)`

忽略模仿Python的

numpy.squeeze

© www.soinside.com 2019 - 2024. All rights reserved.