开发者

Deleting rows containing zero

开发者 https://www.devze.com 2023-03-31 19:54 出处:网络
开发者_Go百科I am trying to find a better way for deleting rows out of some vectors that contain a zero. What I am doing right now is the following code:

开发者_Go百科I am trying to find a better way for deleting rows out of some vectors that contain a zero. What I am doing right now is the following code:

i = 1;
while i <= length(JAbs)
    if JAbs(i) == 0
        JAbs(i) = [];
        JX(i) = [];
    else
        i = i+1;
    end
end

I suppose there is an easier way and would greatly appreciate any help.

Best regards, Achim


>> X=[1 2 3; 3 2 0; 1 2 3;0 3 2]
X =
     1     2     3
     3     2     0
     1     2     3
     0     3     2

removing rows with zeros

X(sum((X==0),2)>0,:) = []

the result:

X =
     1     2     3
     1     2     3


  1. Learn to use vector operations.
  2. Learn to avoid loops, especially bad are loops that chance the size of your arrays in each pass.
  3. Learn to use boolean indexing rather than find. It is faster.

    X(X == 0) = [];

0

精彩评论

暂无评论...
验证码 换一张
取 消