Removing zeros from start of an array and inserting them at the end of same array
    조회 수: 4 (최근 30일)
  
       이전 댓글 표시
    
Let say I have an array 
A = [ 0 0 0 0 1 2 3 4 5 6 7 8 9 0 0 0 0 ]
I would like to know wheter is there any way to move starting four zeros to the end of same array A. 
The result should be 
Result = [ 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 ]
Now, in this example there were only four zeros. I do have arrays which have more than 4 zeros.
Thanks
댓글 수: 0
채택된 답변
  Alex Mcaulley
      
 2019년 3월 13일
        Try this:
A = [0 0 0 0 1 2 3 4 5 6 7 8 9 0 0 0 0];
idx = find(A>0,1);
B = [A(idx:end),zeros(1,idx-1)]
댓글 수: 3
  Alex Mcaulley
      
 2019년 3월 13일
				A = [0 0 0 0 1 2 3 4 5 6 7 8 9 0 0 0 0];
idx = find(A>0,1);
B = [A(idx:end),zeros(1,idx-1)];
B(~B) = max(B);
추가 답변 (2개)
  Sheng Chen
    
 2019년 3월 13일
        Try this
A = [ 0,1,0,3,12];
idx = 1;
for j = 1 : numel(A)
    if A(j) ~= 0
        % swap A(j) and A(idx)
        A([j idx]) = A([idx j]);
        idx = idx + 1;
    end
end
참고 항목
카테고리
				Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



