Azzera filtri
Azzera filtri

Replace zeros with consecutive numbers in a vectors

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

Guillaume
Guillaume il 17 Lug 2015
Modificato: Guillaume il 17 Lug 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 Commento
Guillaume
Guillaume il 17 Lug 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...

Accedi per commentare.

Più risposte (1)

Azzi Abdelmalek
Azzi Abdelmalek il 17 Lug 2015
Modificato: Azzi Abdelmalek il 17 Lug 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)

Categorie

Scopri di più su Historical Contests in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by