Shrink a 1-D array (vector) by removing all the columns with a value of zero

7 visualizaciones (últimos 30 días)
SimpleArray = [1,0,2,0,3,0,4,0,5,0]
Desired result
NewSimpleArray = [1,2,3,4,5]

Respuesta aceptada

Jacob Halbrooks
Jacob Halbrooks el 20 de Mzo. de 2012
Here is a good solution:
NewSimpleArray = SimpleArray(SimpleArray ~= 0)
  4 comentarios

Iniciar sesión para comentar.

Más respuestas (4)

Dr. Seis
Dr. Seis el 20 de Mzo. de 2012
SimpleArray(SimpleArray==0) = [];

David
David el 20 de Mzo. de 2012
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 el 21 de En. de 2018
Editada: seif seif el 21 de En. de 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 comentarios
Image Analyst
Image Analyst el 31 de Ag. de 2018
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
saber kazemi el 12 de Dic. de 2018
How about matrix?
What if the output is still a matrix after removing zero elements?

Iniciar sesión para comentar.


Salam Ismaeel
Salam Ismaeel el 31 de Ag. de 2018
Simply by:
X(X==0)=[]

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by