Remove zeros column and rows from a matrix matlab

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.


1 Dimension:

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

To remove the rows of 0, you can:

  • 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:

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

2 Dimensions:

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

Tags:

Matlab