0
votes

So I want to delete rows of a matrix that contain zero, but only for specific columns. For example:

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

I want for matrix A to check if the second and/or 4th columns contain zero's. If this is true: then delete the whole row. So the result should be:

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

I used this function:

new_a = A(all(A,2),:) 

But I deleted all the rows containing zeros.

2

2 Answers

1
votes

You can write

>>> secondColIsNonzero = A(:, 2) ~= 0;
>>> fourthColIsNonzero = A(:, 4) ~= 0;
>>> keep = secondColIsNonzero & fourthColIsNonzero;
>>> newA = A(keep, :)
newA =
     1     2     0     4
     1     2     3     4
     0     1     2     3

to keep (i.e., not delete) columns where neither the 2nd or 4th column is zero.

For a less verbose solution, consider indexing both columns at the same time and using all with a dimension argument:

keep = all(A(:, [2 4]) ~= 0, 2)
0
votes

This is easily solved using the find() function:

B = A(find(A(:,2)~=0),:)

find() by default returns rows, so calling it in this case returns the index of the rows where the value on the second column is not 0.