Shrink a 1-D array (vector) by removing all the columns with a value of zero
6 次查看(过去 30 天)
显示 更早的评论
SimpleArray = [1,0,2,0,3,0,4,0,5,0]
Desired result
NewSimpleArray = [1,2,3,4,5]
0 个评论
采纳的回答
Jacob Halbrooks
2012-3-20
Here is a good solution:
NewSimpleArray = SimpleArray(SimpleArray ~= 0)
4 个评论
更多回答(4 个)
seif seif
2018-1-21
编辑:seif seif
2018-1-21
Using nonzeros is also very simple (note that the output is a column vector):
NewSimpleArray = nonzeros(SimpleArray)
NewSimpleArray =
1
2
3
4
5
2 个评论
Image Analyst
2018-8-31
That changes the shape from a row vector to a column vector. However it can be fixed with the code below:
SimpleArray = [1,0,2,0,3,0,4,0,5,0] % Row Vector
NewSimpleArray = nonzeros(SimpleArray) % Creates column vector.
% Reshape back into a row vector.
NewSimpleArray = reshape(NewSimpleArray, 1, [])
saber kazemi
2018-12-12
How about matrix?
What if the output is still a matrix after removing zero elements?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!