Shrink a 1-D array (vector) by removing all the columns with a value of zero
조회 수: 8 (최근 30일)
이전 댓글 표시
SimpleArray = [1,0,2,0,3,0,4,0,5,0]
Desired result
NewSimpleArray = [1,2,3,4,5]
댓글 수: 0
채택된 답변
Jacob Halbrooks
2012년 3월 20일
Here is a good solution:
NewSimpleArray = SimpleArray(SimpleArray ~= 0)
댓글 수: 4
추가 답변 (4개)
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
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
2018년 12월 12일
How about matrix?
What if the output is still a matrix after removing zero elements?
참고 항목
카테고리
Help Center 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!