Borrar filtros
Borrar filtros

Replace zeros with consecutive numbers in a vectors

1 visualización (últimos 30 días)
Eli Dim
Eli Dim el 17 de Jul. de 2015
Editada: Azzi Abdelmalek el 17 de Jul. de 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.

Respuesta aceptada

Guillaume
Guillaume el 17 de Jul. de 2015
Editada: Guillaume el 17 de Jul. de 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 comentario
Guillaume
Guillaume el 17 de Jul. de 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...

Iniciar sesión para comentar.

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 17 de Jul. de 2015
Editada: Azzi Abdelmalek el 17 de Jul. de 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)

Categorías

Más información sobre Historical Contests en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by