MATLAB: Add a vector in another vector

add elementsconcatenate

Hello all,
I have a vector (for example A=rand(1,100);) and I would like to add another vector which is B=zeros(1,10); to A before each index that I want.
For instance, I would like to add vector B in vector A before index 5. The result should be a vector with 110 elements which the first four elements are the same as first four elements of A then I should have 10 zeros then all elements of vector A after the fifth element. I hope my question be clear enough.
Thanks a lot.

Best Answer

The code below should work.
A=rand(1,100);
B=zeros(1,10);
wanted_index=5;
if wanted_index==1
result=[B A];
elseif wanted_index>numel(A)
result=[A B];
else
result=[A(1:(wanted_index-1)) B A(wanted_index:end)];
end