removing zero element rows in a m×n matrix?

조회 수: 1 (최근 30일)
Rakesh Praveen
Rakesh Praveen 2011년 11월 11일
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

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by