简体   繁体   English

从矩阵中删除零列和行 matlab

[英]Remove zeros column and rows from a matrix matlab

I would like to remove some columns and rows from a big matrix.我想从一个大矩阵中删除一些列和行。 Those are the columns and the rows which have all zeros values.这些是全零值的列和行。 Is there any function in MATLAB that can do it for you quite fast? MATLAB里面有没有function可以给你做的比较快的? My matrices are sparse.我的矩阵很稀疏。 I am doing this way:我这样做:

 % To remove all zero columns from A
 ind = find(sum(A,1)==0) ;
 A(:,ind) = [] ;

 % To remove all zeros rows from A
 ind = find(sum(A,2)==0) ;
 A(ind,:) = [] ;

It would be nice to have a line of code for this as I may do this kind of task repeatedly.最好为此编写一行代码,因为我可能会重复执行此类任务。 Thanks谢谢

A single line of code would be: 一行代码是:

A=A(any(X,2),any(X,1))

There is no need to use find like you did, you can directly index using logical vectors. 没有必要像你一样使用find ,你可以使用逻辑向量直接索引。

1 Dimension: 1 维度:

I'll first show a simpler example based on another duplicate question , asking to to remove only the rows containing zeros elements.我将首先展示一个基于另一个重复问题的更简单的示例,要求仅删除包含零元素的

Given the matrix A=[1,2;0,0];给定矩阵A=[1,2;0,0];

To remove the rows of 0 , you can:要删除0的行,您可以:

  • sum the absolute value of each rows (to avoid having a zero sum from a mix of negative and positive numbers), which gives you a column vector of the row sums.对每行的绝对值求和(以避免负数和正数的混合为零),这会为您提供行总和的列向量。

  • keep the index of each line where the sum is non-zero.保留总和非零的每一行的索引。

in code:在代码中:

A=[1,2;0,0];
% sum each row of the matrix, then find rows with non-zero sum
idx_nonzerolines = sum(abs(A),2)>0 ;
% Create matrix B containing only the non-zero lines of A
B = A(idx_nonzerolines,:) ;

will output:将 output:

>> idx_nonzerolines = sum(abs(A),2)>0
idx_nonzerolines =
     1
     0
>> B = A(idx_nonzerolines,:)
B =
     1     2

2 Dimensions: 2 尺寸:

The same method can be used for 2 dimensions:同样的方法可以用于二维:

A=[ 1,2,0,4;
    0,0,0,0;
    1,3,0,5];

idx2keep_columns = sum(abs(A),1)>0 ;
idx2keep_rows    = sum(abs(A),2)>0 ;

B = A(idx2keep_rows,idx2keep_columns) ;

outputs:输出:

>> B = A(idx2keep_rows,idx2keep_columns)
B =
     1     2     4
     1     3     5

Thanks to @Adriaan in comments for spotting the edge case;)感谢@Adriaan 在评论中发现边缘情况;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM