filling a vector up with a second one

조회 수: 1 (최근 30일)
Matt
Matt 2012년 12월 2일
Hello,
My Problem: 2 vectors a and b. a=[0;0;0;0;0;5;5;5;4;4] b=[1;1;1;4;4;5;5;5;6;6;9;9;10;10;10;11]
My goal is to replace the 0's in a with the last entries of b and I have no idea how to realise this.
the resulting vector a should look like this: a=[9;10;10;10;11;5;5;5;4;4]
vector b is sorted thanks in advance for your participation!
  댓글 수: 1
Azzi Abdelmalek
Azzi Abdelmalek 2012년 12월 2일
Can you have a as [0;0;5;5;0;0;4;4;0;0]

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

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 12월 2일
편집: Azzi Abdelmalek 2012년 12월 2일
a=[0;0;0;0;0;5;5;5;4;4]
b=[1;1;1;4;4;5;5;5;6;6;9;9;10;10;10;11]
idx=find(~a);
a(idx)=b(end-length(idx)+1:end)

추가 답변 (2개)

Image Analyst
Image Analyst 2012년 12월 2일
Try this:
lastZero = find(a==0, 1, 'last') % Find index of the last zero in a
a(1:lastZero) = b(end-lastZero+1:end) % Replace with elements from b
This will work with situations where a starts with a stretch of zeros and that is where all the zeros are. If you have a different situation, then you should say so, and give an alternate example.

Matt
Matt 2012년 12월 2일
Hi thanks a lot for your answers, they work both!
what could I do if a was
a=[0;0;0;0;0;5;5;5;4;4;0;0]
and i like to receive:
a=[9;10;10;10;11;5;5;5;4;4;0;]
?
thx!
  댓글 수: 2
Image Analyst
Image Analyst 2012년 12월 2일
You need to clarify the rule. The rule as I see it is the same as before except that if there is a stretch of zeros at the end you either lop off all but one, or shorten the ending stretch of zeros by one element.
Azzi Abdelmalek
Azzi Abdelmalek 2012년 12월 2일
편집: Azzi Abdelmalek 2012년 12월 2일
idx=find(~a)
d=find(diff(idx)~=1,1);
a(1:d)=b(end-d+1:end);
test=0;
k=0;
while test==0
if a(end-k)==0
a(end)=[]
k=1;
else
test=1;
end
end

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

카테고리

Help CenterFile Exchange에서 Hypothesis Tests에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by