필터 지우기
필터 지우기

Replace zeros with consecutive numbers in a vectors

조회 수: 1 (최근 30일)
Eli Dim
Eli Dim 2015년 7월 17일
편집: Azzi Abdelmalek 2015년 7월 17일
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.

채택된 답변

Guillaume
Guillaume 2015년 7월 17일
편집: Guillaume 2015년 7월 17일
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
Guillaume
Guillaume 2015년 7월 17일
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...

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 17일
편집: Azzi Abdelmalek 2015년 7월 17일
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)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by