MATLAB: Deleting columns in a matrix if any of the rows are 0s

arraycolumndeleteelementemptyMATLABmatrixremoverow

I have a matrix with some zeros in it. What is the best way to remove any of the columns that contain a zero?

Best Answer

You can extract which columns have a zero element using the "any" function, and then assign those columns to empty to remove them from the matrix. This can be done in one line using logical indexing. See the example below:
% Setup matrix with a zero in columns 4 and 6
A = ones(10);
A(2,4) = 0;
A(3,6) = 0;
% Remove columns that contain a zero
A( :, any(A==0) ) = [];