removing zero element rows in a m×n matrix?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuesta aceptada
Walter Roberson
el 11 de Nov. de 2011
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),:) = [];
2 comentarios
Walter Roberson
el 11 de Nov. de 2011
The 2 means to work across the second dimension, which is across rows in MATLAB. The first dimension is columns and is the default direction for the majority of MATLAB operations.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!