Shrink a 1-D array (vector) by removing all the columns with a value of zero
Afficher commentaires plus anciens
SimpleArray = [1,0,2,0,3,0,4,0,5,0]
Desired result
NewSimpleArray = [1,2,3,4,5]
Réponse acceptée
Plus de réponses (4)
Dr. Seis
le 20 Mar 2012
SimpleArray(SimpleArray==0) = [];
David
le 20 Mar 2012
0 votes
Using nonzeros is also very simple (note that the output is a column vector):
NewSimpleArray = nonzeros(SimpleArray)
NewSimpleArray =
1
2
3
4
5
2 commentaires
Image Analyst
le 31 Août 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
le 12 Déc 2018
How about matrix?
What if the output is still a matrix after removing zero elements?
Salam Ismaeel
le 31 Août 2018
0 votes
Simply by:
X(X==0)=[]
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!