55

在 GNU Octave 中,我希望能够从矩阵中删除特定的列。为了一般性。我还希望能够从矩阵中删除特定行。

假设我有这个:

mymatrix = eye(5)

mymatrix =

Diagonal Matrix

   1   0   0   0   0
   0   1   0   0   0
   0   0   1   0   0
   0   0   0   1   0
   0   0   0   0   1

我想删除第 2 列和第 4 列,但是当我删除第 2 列时,第 4 列的位置已经移动到第 3 列,这让我很头疼。一定有更好的方法!

4

4 回答 4

77

如果您不知道确切的列数或行数,您可以使用神奇的“结束”索引,例如:

mymatrix(:,2:end)  % all but first column

mymatrix(2:end,:)  % all but first row

这还允许您从矩阵中切出行或列,而无需将其重新分配给新变量。

于 2014-11-12T15:00:05.693 回答
62

GNU Octave delete Columns 2 and 4 from a Matrix

mymatrix = eye(5); 
mymatrix(:,[2,4]) = []; 
disp(mymatrix)

Prints:

1   0   0
0   0   0
0   1   0
0   0   0
0   0   1

GNU Octave delete Rows 2 and 4 from a Matrix:

mymatrix = eye(5); 
mymatrix([2,4],:) = [];
disp(mymatrix) 

Prints:

1   0   0   0   0
0   0   1   0   0
0   0   0   0   1

Time complexity

GNU Octave's CPU complexity for slicing and broadcasting here is a fast linear time O(n * c) where n is number of rows and c a constant number of rows that remain. It's C level single-core vectorized but not parallel.

Memory complexity

Working memory complexity is linear: O(n * 2) C makes a clone of the two objects, iterates over every element, then deletes the original.

The only time speed will be a problem is if your matrices are unrealistically wide, tall, or have a number of dimensions that blow out your fast memory, and speed is limited by the transfer speed between disk and memory.

于 2012-09-12T14:27:30.503 回答
14

执行此操作的相反方法:

columns_you_want_to_keep = [1, 3, 5]
new_matrix = my_matrix(:,columns_you_want_to_keep)
于 2013-11-25T11:37:22.957 回答
9

如何删除八度音阶中的多个列:

如何删除第 2 列和第 4 列:

columns_to_remove = [2 4];
matrix(:,columns_to_remove)=[]

插图:

mymatrix = eye(5)
mymatrix =

   1   0   0   0   0
   0   1   0   0   0
   0   0   1   0   0
   0   0   0   1   0
   0   0   0   0   1



columns_to_remove = [2 4];

mymatrix(:,columns_to_remove)=[]


mymatrix =

   1   0   0
   0   0   0
   0   1   0
   0   0   0
   0   0   1 
于 2012-09-12T14:29:36.463 回答