从矩阵中提取每第n列

时间:2018-05-03 09:48:59

标签: matlab matrix matrix-indexing submatrix

我需要从矩阵中提取每个第n列。

例如,我有一个矩阵:

A =
     1    23    34    53    67    45    67    45
    12    34    45    56    67    87    98    12
     1     2     3    45    56    76    87    56

我想提取每组三列,即删除每四列。我的数据应该是:

X =
     1    23    34    67    45    67
    12    34    45    67    87    98
     1     2     3    56    76    87

所以我会跳过第4列,然后是第8列,依此类推。我知道如何提取每个第n列和行,但我无法弄清楚如何使用它来获得我需要的东西。

4 个答案:

答案 0 :(得分:4)

如果你想"保存"每隔四列,语法就是:

toKeep = 4:4:8;
A = rand(3,8) % Insert your matrix
B = A(:,toKeep);

即。您将这些值分配给新矩阵。在你的情况下,你想要删除它们,因此你可以简单地为这些地方分配一个空矩阵,实际上删除它们。

toRemove = 4:4:8; %Every fourth column
A = rand(3,8) % Insert your matrix
A(:,toRemove) = [];

编辑1

正如Wolfie在评论中正确指出的那样,您可以通过将toRemoveA(:,toRemove)一起编写并使用end关键字来改善这一点,以便您拥有:

A = rand(3,8) % Insert your matrix
A(:,4:4:end) = [];

在这种情况下,您不必担心矩阵的大小。

编辑2:

对于没有句号的一般情况,这种方法当然也有效。变量toRemove只需要包含要删除的列的索引,例如

toRemove = randperm(8,randi(5)); %Select up to 5 random columns to remove
A = rand(3,8) % Insert your matrix
A(:,toRemove) = [];

PS。如果您想保留原始矩阵A,您可以先将其分配给B=A;,然后再在B上执行操作。

答案 1 :(得分:2)

A = rand(3,8) % Insert your matrix
n = 4; % Index of column to skip
idx = 1:size(A,2) % create indexing array
B = A(:,mod(idx,n)~=0) % logically index
A =
    0.7094    0.6797    0.1190    0.3404    0.7513    0.6991    0.5472    0.2575
    0.7547    0.6551    0.4984    0.5853    0.2551    0.8909    0.1386    0.8407
    0.2760    0.1626    0.9597    0.2238    0.5060    0.9593    0.1493    0.2543
idx =
     1     2     3     4     5     6     7     8
B =
    0.7094    0.6797    0.1190    0.7513    0.6991    0.5472
    0.7547    0.6551    0.4984    0.2551    0.8909    0.1386
    0.2760    0.1626    0.9597    0.5060    0.9593    0.1493

这里的想法是你创建一个索引数组idx,然后检查所需idx的{​​{1}}除以等于零的位置。无论何时,您都想跳过该列。打破它:

n

然后我们可以在mod(idx,n) % 0 whenever idx is entirely divisible by n mod(idx,n)==0 % finds where the zeros are ~(mod(idx,n)==0) % finds wherever the non-zeros are, i.e. the columns we want 中的列上使用最后一个logical index来生成所需的输出。

单行,因为我们可以:

A

答案 2 :(得分:0)

  

对于要排除的列的ID中不存在明确周期的情况,这是一种稍微更通用的解决方案;添加完整性。

假设您的矩阵A包含N列,并且您想要排除其ID位于向量E中的列,则可以使用setdiff函数进行演示下面:

N = randi([30 50]);        % Generate data size
A = randi(N^2,N,N);        % Generate data
E = randperm(N,randi(10)); % Define column ids to exclude
X = A(:,setdiff(1:N,E));   % Create output

应用于您的示例,它看起来像这样:

S = size(A,2);
X = A(:, setdiff(1:S,4:4:S) ); % No need for the intermediate variable E

答案 3 :(得分:0)

构建列索引的向量很简单,您可以通过多种方式实现。例如,如果要跳过每个第n列,矩阵中有N列:

I = (1:n-1).'+(0:n:N-1);

请注意,+适用于所有维度;在旧版本的Matlab中,您应该使用bsxfun代替。

在您的情况下,n=4N=8I是:

1    5
2    6
3    7

然后你只用索引获得矩阵:

X = A(:,I);