MATLAB: Removing zero element rows in a m×n matrix

matrix manipulation

i want to remove the rows which contain all zeros. so finally i expect a matrix containing with the remaining rows. I use a 'for loop' to represent each row, but then i get a error "Index of element to remove exceeds matrix dimensions". help me to get rid of these zero elemental rows. thank you. example: a =[0 0 0 0
1 2 3 4
2 0 1 1
0 0 0 0]
new_a =a;
for i=1:4
if a(i,:)==0
new_a(i,:)=[];
end
end
new_a

Best Answer

That is a common error. After you assign [] to remove a row, the matrix now has fewer rows, but you proceed as if it still has as many rows as it used to have. Eventually you will index a row that no longer exists.
Easiest fix: loop backwards, so that the rows you have not examined yet will not have been moved.
Better fix: use logical indexing and do everything at the same time:
new_a = a(any(a,2),:);
or
new_a = a;
new_a(~any(a,2),:) = [];