# filling a vector up with a second one

1 view (last 30 days)
Matt on 2 Dec 2012
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]
Azzi Abdelmalek on 2 Dec 2012
Can you have a as [0;0;5;5;0;0;4;4;0;0]

Azzi Abdelmalek on 2 Dec 2012
Edited: Azzi Abdelmalek on 2 Dec 2012
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)

Image Analyst on 2 Dec 2012
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 on 2 Dec 2012
what could I do if a was
a=[0;0;0;0;0;5;5;5;4;4;0;0]
a=[9;10;10;10;11;5;5;5;4;4;0;]
?
thx!
##### 2 CommentsShowHide 1 older comment
Azzi Abdelmalek on 2 Dec 2012
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