175k views
0 votes
Write a function called interweave that takes in two vectors and then outputs a larger vector where the odd elements contain the values from the first vector, and the even elements contain the values from the second vector. if one vector is longer than the other, then the odd or even indices that wouldn't otherwise have values should be filled with zeros. for

1 Answer

4 votes

solution:

function weaved=interweave(A,B)

lenA=length(A);

lenB=length(B);

diff=abs(lenA-lenB);

if lenA>lenB

len=2*lenA;

for j=(lenB+1):(lenB+diff)%adds zero to shorter vector

B(j)=0;

end

else

len=2*lenB;

for j=(lenA+1):(lenA+diff)%adds zero to shorter vector

A(j)=0;

end

end

cnt=1;

for i=1:2:(len-1)

weaved(i)=A(cnt);

weaved(i+1)=B(cnt);

cnt=cnt+1;


User Jpskgc
by
8.1k points