フィルターのクリア

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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by