Filter löschen
Filter löschen

Replace zeros with consecutive numbers in a vectors

1 Ansicht (letzte 30 Tage)
Eli Dim
Eli Dim am 17 Jul. 2015
Bearbeitet: Azzi Abdelmalek am 17 Jul. 2015
I have a large column vector which looks like this:
A=[1;2;3;4;5;1;5;6;..................;2305;0;0;0;0]
I want to replace the zeros in the end so the new vector looks like this:
A=[1;2;3;4;5;1;5;6;..................;2305;2306;2307;2308;2309]
How can I do this without a loop? The vector changes its size after every iteration, but I always have a couple of zeros in the end.

Akzeptierte Antwort

Guillaume
Guillaume am 17 Jul. 2015
Bearbeitet: Guillaume am 17 Jul. 2015
There are many ways you could do this. If the zeros are always at the end with no zero beforehand, this will work:
A = [nonzeros(A); A(find(A == 0, 1)-1) + (1:sum(A==0))']
  1 Kommentar
Guillaume
Guillaume am 17 Jul. 2015
And if there can be zeros before the end, this only replaces the zeros at the very end:
lastnumberidx = find(A~=0, 1, 'last');
A = [A(1:lastnumberidx); A(lastnumberidx) + (1:numel(A)-lastnumberidx)']
As I said, plenty of ways...

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Azzi Abdelmalek
Azzi Abdelmalek am 17 Jul. 2015
Bearbeitet: Azzi Abdelmalek am 17 Jul. 2015
This takes in account all zeros
A=[1 ;2; 7;0; 0 ;4;8;0;6;7;18;0;0;0;12;0 ;0 ;13]
A=A'
idx1=A==0 ;
ii1=strfind([0 idx1 0],[ 0 1]);
jj=strfind([0 idx1 0],[1 0])-ii1;
[B,C,CC]=deal(zeros(size(A)));
B(ii1)=[0 jj(1:end-1)];
qq=cumsum(idx1).*idx1;
aa=(qq-cumsum(B)).*idx1;
[C(ii1-1),aa(ii1-1)]=deal(A(ii1-1));
CC(ii1-1)=[0 A(ii1(1:end-1)-1)];
DD=cumsum(C-CC).*idx1+aa;
A(idx1)=DD(idx1)

Kategorien

Mehr zu Historical Contests finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by