Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Function Name: interweave % Inputs (2): - (double) A 1xN vector of numbers % - (

ID: 3648429 • Letter: F

Question

Function Name: interweave
% Inputs (2): - (double) A 1xN vector of numbers
% - (double) A 1xN vector of numbers
% Outputs (1): - (double) A vector of the two vectors mixed together
%
% Function Description:
% Write a function called "interweave" that takes in two vectors and then
% returns one larger vector where all of the elements at the odd indicies
% contain the values from the first vector and all the elements at the
% even indices contain the values from the second vector. If one vector
% is longer than the other,the remaining indices should be filled with
% zeros.
%
% Hints:
% - The length of the final vector should be twice the length of the
% longest vector.
% - You may find the max() and zeros() function useful.
%
% Test Cases:
% mixed1 = interweave([1 2 3 4 5],[6 7 8 9 10]);
% mixed1 => [1 6 2 7 3 8 4 9 5 10]
%
% mixed2 = interweave([5 1 5 9 1], [4 1 3]);
% mixed2 => [5 4 1 1 5 3 9 0 1 0]
%
% mixed3 = interweave([8 6 7], [5 3 0 9]);
% mixed3 => [8 5 6 3 7 0 0 9]

Explanation / Answer

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; end