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