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]

采纳的回答

Jacob Halbrooks
Jacob Halbrooks 2012-3-20
Here is a good solution:
NewSimpleArray = SimpleArray(SimpleArray ~= 0)
  4 个评论

请先登录,再进行评论。

更多回答(4 个)

Dr. Seis
Dr. Seis 2012-3-20
SimpleArray(SimpleArray==0) = [];

David
David 2012-3-20
Thanks for the answers and for showing me the previous discussion string (I didn't think this was the first time this question was asked)

seif seif
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
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, [])

请先登录,再进行评论。


Salam Ismaeel
Salam Ismaeel 2018-8-31
Simply by:
X(X==0)=[]

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by