Shrink a 1-D array (vector) by removing all the columns with a value of zero
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
SimpleArray = [1,0,2,0,3,0,4,0,5,0]
Desired result
NewSimpleArray = [1,2,3,4,5]
0 Commenti
Risposta accettata
Jacob Halbrooks
il 20 Mar 2012
Here is a good solution:
NewSimpleArray = SimpleArray(SimpleArray ~= 0)
4 Commenti
Più risposte (4)
seif seif
il 21 Gen 2018
Modificato: seif seif
il 21 Gen 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 Commenti
Image Analyst
il 31 Ago 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
il 12 Dic 2018
How about matrix?
What if the output is still a matrix after removing zero elements?
Vedere anche
Categorie
Scopri di più su Multidimensional Arrays in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!