MATLAB: How to delete certain rows of a matrix based on specific column values

delete rowsmatrix manipulationremoverows remove rows

I have a matrix that has 6 columns and thousands of rows.
I need to delete the rows based on the following conditions:
1. if column 1 is zero then delete row
2. if column 2,3,4,and 5 is zero, and column 6 is not zero, then delete row
3. if column 2,3,and 4 is zero, and column 5 is not zero, then delete row
4. if column 2,and 3 is zero, and column 4 is not zero, then delete row
5. if column 2 is zero, and column 3 is not zero, then delete row
Someone please help, I feel like I've tried everything!

Best Answer

This is a job for logical indexing! Note that you do not need to loop over all the lines at all
Assume A is your matrix. Here is a short example (not tested):
A = [0 2 3 4 5 6 ; 11 0 0 0 15 16 ; 21 0 0 0 0 26 ; 31 0 33 34 35 36 ; 41 42 43 0 0 0]
% Specify you conditions
TF1 = A(:,1)==0
TF2 = all(A(:,2:5)==0,2) & A(:,6) ~= 0
TF6 = A(:,2) == 0 & A(:,3) A ~= 0
% combine them
TFall = TF1 & TF2 & TF6
% remove
A(TFall,:) = []