Replace zeros with consecutive numbers in a vectors
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Guillaume
on 17 Jul 2015
Edited: Guillaume
on 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 Comment
Guillaume
on 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...
More Answers (1)
Azzi Abdelmalek
on 17 Jul 2015
Edited: Azzi Abdelmalek
on 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)
0 Comments
See Also
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!