フィルターのクリア

How to delete rows with values 0 from matrix

1 回表示 (過去 30 日間)
Simon Spielmann
Simon Spielmann 2023 年 5 月 1 日
コメント済み: Simon Spielmann 2023 年 5 月 1 日
Hello,
I have matrix A which looks like
A = [0 0 0; 0 0 0; 5 1 0; 0 0 0; 1 0 3; 5 9 5; 0 0 0]
I am trying delete all rows in which all values are 0 from matrix A to get:
A = [5 1 0; 1 0 3; 5 9 5]
I used this.
for i = 1:length(A(:,1))
while A(i,1) == 0 && A(i,2) == 0 && A(i,3) == 0
A(i,:) = [];
end
end
At the end it gives me matrix A but also it gives me a error:
'Index in position 1 exceeds array bounds. Index must not exceed 4.' but do not know why...
  2 件のコメント
VBBV
VBBV 2023 年 5 月 1 日
A = [0 0 0; 0 0 0; 5 1 0; 0 0 0; 1 0 3; 5 9 5; 0 0 0]
A = 7×3
0 0 0 0 0 0 5 1 0 0 0 0 1 0 3 5 9 5 0 0 0
i = 1;
while i <= length(A)
if isequal(A(i,1),0) & isequal(A(i,2), 0) & isequal(A(i,3), 0)
A(i,:) = [];
% tricky part lies in next line
i = i-1;
end
i = i+1 ;
end
A
A = 3×3
5 1 0 1 0 3 5 9 5
Simon Spielmann
Simon Spielmann 2023 年 5 月 1 日
Than you a lot, it really helps!

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

回答 (1 件)

KSSV
KSSV 2023 年 5 月 1 日
A = [0 0 0; 0 0 0; 5 1 0; 0 0 0; 1 0 3; 5 9 5; 0 0 0]
A = 7×3
0 0 0 0 0 0 5 1 0 0 0 0 1 0 3 5 9 5 0 0 0
A(~any(A,2),:) = []
A = 3×3
5 1 0 1 0 3 5 9 5
  1 件のコメント
Simon Spielmann
Simon Spielmann 2023 年 5 月 1 日
Than you a lot, it really helps!

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by