Shrink a 1-D array (vector) by removing all the columns with a value of zero
17 views (last 30 days)
Show older comments
SimpleArray = [1,0,2,0,3,0,4,0,5,0]
Desired result
NewSimpleArray = [1,2,3,4,5]
0 Comments
Accepted Answer
Jacob Halbrooks
on 20 Mar 2012
Here is a good solution:
NewSimpleArray = SimpleArray(SimpleArray ~= 0)
4 Comments
More Answers (4)
seif seif
on 21 Jan 2018
Edited: seif seif
on 21 Jan 2018
Using nonzeros is also very simple (note that the output is a column vector):
NewSimpleArray = nonzeros(SimpleArray)
NewSimpleArray =
1
2
3
4
5
2 Comments
saber kazemi
on 12 Dec 2018
How about matrix?
What if the output is still a matrix after removing zero elements?
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!