how do I interleave 2 arrays of different sizes?

Interleave advanced
Modify the function interleave, written in a previous assignment, to create a function called interleaveMod. interleaveMod interleaves two row arrays of different lengths named A2 and B2. If the function runs out of elements in one of the row arrays, the remaining elements of the resulting array keeps the remaining elements from the longer row array. The function should work for rows of any length.
Hint: The internal functions length and min, and array indexing should be used.
Restrictions: For and while loops should not be used.
Ex:
>> A2 = [1, 2, 3, 4, 5, 6] , B2 = [10, 20, 30], C3= interleaveMod(A2,B2)
A2 =
1 2 3 4 5 6
B2 =
10 20 30
C3 =
1 10 2 20 3 30 4 5 6

3 Comments

I have posted complete code for this task in the past. Might be a bit difficult to find, though, as it did not use this exact wording. A solution from someone else is a bit easier to find.
"Hint: The internal functions length... should be used."
This is bad advice: length is problematic as the dimension it measures changes with the size of the input variable. It is much more reliable to use numel and size, and learn to use these for all code. When beginners learn to avoid using length then their code becomes more robust as a result. Read these to know more:
Although in this simple case using vectors length will work, using numel and size are a much better code practice for beginners to learn. Even experienced MATLAB users get confused about what length actually does, for example:

Sign in to comment.

 Accepted Answer

>> A = [1,2,3,4,5,6];
>> B = [10,20,30];
>> N = min(numel(A),numel(B));
>> C = [reshape([A(1:N);B(1:N)],1,[]),A(N+1:end),B(N+1:end)]
C =
    1    10     2    20     3    30     4     5     6

3 Comments

can somebody explain this?
Break it down into steps. Figure out what the steps do, and if you get stuck, ask about a specific part.

Sign in to comment.

More Answers (1)

function [ arrayThree ] = interleaveMod( arrayOne,arrayTwo )
C1= [arrayOne;arrayTwo];
arrayThree =C1(:); % complete the code
arrayThree=transpose(arrayThree)
How would I modify this for interleaveMod?

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!