简体   繁体   中英

Remove zeros from matrix in matlab

I have a question and I hope it is not duplicate.

First, I have let say the following matrix:

A=[2 2 2 0 0
   1 2 3 0 0
   4 5 7 2 0]

I want to remove the zeros from A and return:

A=[2 2 2
   1 2 3
   4 5 7]

When I do

A(A==0)=[] 

I get

A=[2 2 2 1 2 3 4 5 7]

Second, if instead of zeros I want to remove the elements that are greater than something. For example if I want to remove all elements greater than 6 (>6) of the following matrix B:

B=[2 2 2 5 3
   1 2 3 6 8
   4 5 7 2 1]

I get

A=[2 2 5
   1 2 6
   4 5 2]

PS I know how to do it using loops.

First problem solution

A(:,find(all(A,1)))

Second problem solution

B(:,~any(B>6,1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM