MATLAB: For-loops, i, and vector accessing: I can’t see the obvious

for looprewritevector

Hello everyone,
I am using a for-loop to access and write vectors. I have an incomplete vector A which lacks every second entry. Those missing data can be derived from the existing data. By using a for-loop, I want to add the missing values. Unfortunately, I seem to be stuck with my mental set and am unable to correct my code myself.
This is a simplified version of my problem:
% A are the original, incomplete data.
A = [0 2 4 6 8] % The missing data would be 1 3 5 7 9 in this case.
B = [] % B will be the vector that contains both the original and the reconstructed data; thus, B is the "complete vector" and should once contain [0 1 2 3 4 5 6 7 8 9]
% The following loop should fill B with one number from A and one reconstructed number.
>> for i = 1:2:5
B(i) = A(i);
B(i+1) = A(i)+1;
end
>> B
B =
0 1 4 5 8 9
As you can see, B is 0 1 4 5 8 9 — it seems that my for-loop accidentally overwrites parts of B that have been created earlier. However, I am unable to see how I can correct this. I've spent hours figuring this out, but I seem to be unable to find the obvious solution. Can someone help?
Regards,
Chris

Best Answer

Code revision:
for i = 1:length(A)
B(2*i-1) = A(i);
B(2*i) = A(i)+1;
end
Your code was not overwriting B, it was skipping parts of A.
Related Question