Filter löschen
Filter löschen

removing zero element rows in a m×n matrix?

1 Ansicht (letzte 30 Tage)
Rakesh Praveen
Rakesh Praveen am 11 Nov. 2011
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 11 Nov. 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 Kommentare
Rakesh Praveen
Rakesh Praveen am 11 Nov. 2011
Thanks now its working. when u say any(a,2) what does the 2 mean ?
Walter Roberson
Walter Roberson am 11 Nov. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by