Add a vector in another vector

41 views (last 30 days)
hamed
hamed on 28 May 2018
Commented: hamed on 28 May 2018
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.

Accepted Answer

Rik
Rik on 28 May 2018
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

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices 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!