Delete rows from a matrix using for loop

5 ビュー (過去 30 日間)
Juan Pérez Álvarez
Juan Pérez Álvarez 2022 年 2 月 22 日
コメント済み: Dominique 2023 年 11 月 6 日
Hello, I need delete the zero rows from a matrix using for loops/while, I try this:
Matrix = [1,1 ; 1,2 ; 0,0 ; 0,0 ; 3,1 ; 0,0];
LM =length(Matrix);
cont = 0;
for i = 1 : LM
if Matrix(i) == 0
cont = cont + 1;
end
end
Matrix_Aux = [];
for j = 1:LM
if Matrix(j) ~= 0
Matrix_Aux = [Matrix(j)];
end
end
I need get this:
Matrix_Aux = [1,1 ; 1,2 ; 3,1 ];
Any idea?

採用された回答

David Hill
David Hill 2022 年 2 月 22 日
Forcing to use for-loop
Matrix = [1,1 ; 1,2 ; 0,0 ; 0,0 ; 3,1 ; 0,0];
idx=[];
for k=1:size(Matrix,1)
if all(Matrix(k,:)==0)
idx=[idx,k];
end
end
Matrix(idx,:)=[];
  1 件のコメント
Dominique
Dominique 2023 年 11 月 6 日
Thanks. Good solution.

サインインしてコメントする。

その他の回答 (1 件)

Voss
Voss 2022 年 2 月 22 日
編集済み: Voss 2022 年 2 月 22 日
No loops are necessary:
Matrix = [1 1; 1 2; 0 0; 0 0; 3 1; 0 0]
Matrix = 6×2
1 1 1 2 0 0 0 0 3 1 0 0
Matrix(all(Matrix == 0,2),:) = []
Matrix = 3×2
1 1 1 2 3 1

カテゴリ

Help Center および File ExchangeMatrix Computations についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by