I wrote the code according to my lesson but it keeps inserting a 0 between each number in the array.
It doesn't so much insert a 0 between each number in the array so much as not assigning to certain elements in the array. Let me add a little diagnostic code to what you wrote. I'm also only going to work on A as B has the same behavior and I'm changing the vector over which your for loop operates just so we display fewer lines.
fprintf("Before assigning to element %d of A, A has length %d.\n", i+1, length(A))
fprintf("Assigning %d to element %d of A.\n", i^2, i+1)
fprintf("After assigning to element %d of A, A has length %d.\n \n", i+1, length(A))
end
Before assigning to element 1 of A, A has length 0.
Assigning 0 to element 1 of A.
After assigning to element 1 of A, A has length 1.
Before assigning to element 3 of A, A has length 1.
Assigning 4 to element 3 of A.
After assigning to element 3 of A, A has length 3.
Before assigning to element 5 of A, A has length 3.
Assigning 16 to element 5 of A.
After assigning to element 5 of A, A has length 5.
Before assigning to element 7 of A, A has length 5.
Assigning 36 to element 7 of A.
After assigning to element 7 of A, A has length 7.
A
A =
0 0 4 0 16 0 36
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
All the values in the vector over which you're iterating are even. You only ever assign to the elements at locations that are the values in that vector plus 1, so you only ever assign to the odd element locations. But MATLAB can't leave "holes" in the vector, so when it grows the vector it has to fill in the even element locations (that you're skipping over) with something. That something, for a double array, is 0.
To avoid skipping elements, either perform a computation on the value of i to map between the values 0:2:n and the indices 1:m or keep a variable with the index of the next element to fill in.
fprintf("Assigning %d to element %d of A.\n", i^2, (i/2)+1)
fprintf("Assigning %d to element %d of C.\n", i^2, nextCloc)
end
Assigning 0 to element 1 of A.
Assigning 0 to element 1 of C.
Assigning 4 to element 2 of A.
Assigning 4 to element 2 of C.
Assigning 16 to element 3 of A.
Assigning 16 to element 3 of C.
Assigning 36 to element 4 of A.
Assigning 36 to element 4 of C.