delete zeros from matrix

조회 수: 4 (최근 30일)
Maria K
Maria K 2020년 7월 23일
답변: Bruno Luong 2020년 7월 23일
How do I delete all the columns that have zeros with a for loop? I tried reducing the number of columns by one in every iteration but matlab shows me "index exceeds matrix dimentions".
p4 = [0 0 31 37 43 47; 0 0 19 13 7 3];
grammes = size(p3,1);
sthles = size(p3,2);
for i = 1 : grammes
for j = 1 : sthles
if iszero(p3(i,j)) == 1
p3(:,j) = [];
sthles = sthles - 1
end
end
end
  댓글 수: 1
Maria K
Maria K 2020년 7월 23일
Thanks on advance!

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

채택된 답변

Bruno Luong
Bruno Luong 2020년 7월 23일
Here is how using FOR-LOOP to delete zero column(s)
A = [0 0 31 37 43 47;
0 0 19 13 7 3];
[m,n] = size(A);
for j = n:-1:1 % must loop reversing
deleteflag = true;
for i = 1 : m
if A(i,j) ~= 0
deleteflag = false;
end
end
if deleteflag % only true if the entire column #j contains 0s
A(:,j) = [];
end
end

추가 답변 (1개)

madhan ravi
madhan ravi 2020년 7월 23일
p4(:, all(p4 == 0)) = []
  댓글 수: 1
Maria K
Maria K 2020년 7월 23일
Cool answer but I would like to know how to do it with a for loop..

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

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by