Removing zeros from start of an array and inserting them at the end of same array

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Alex Mcaulley
Alex Mcaulley am 13 Mär. 2019
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 Kommentare
Alex Mcaulley
Alex Mcaulley am 13 Mär. 2019
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);
Shahab Khan
Shahab Khan am 13 Mär. 2019
Thank you, actually i figured that out myself so i deleted the question. But anyway Thanks alot.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Matt J
Matt J am 13 Mär. 2019
Bearbeitet: Matt J am 13 Mär. 2019
n=find(A,1);
Result=circshift(A,1-n);

Sheng Chen
Sheng Chen am 13 Mär. 2019
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

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by