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

7 ビュー (過去 30 日間)
David
David 2012 年 3 月 20 日
コメント済み: Saad Rehman 2019 年 5 月 7 日
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 件のコメント
Kaveh Allahdin
Kaveh Allahdin 2018 年 11 月 14 日
How would you do this in simulink?
Saad Rehman
Saad Rehman 2019 年 5 月 7 日
thanks brother

サインインしてコメントする。

その他の回答 (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, [])
saber kazemi
saber kazemi 2018 年 12 月 12 日
How about matrix?
What if the output is still a matrix after removing zero elements?

サインインしてコメントする。


Salam Ismaeel
Salam Ismaeel 2018 年 8 月 31 日
Simply by:
X(X==0)=[]

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by