Removing zeros from start of an array and inserting them at the end of same array
1 次查看(过去 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!