Add a vector in another vector

65 visualizaciones (últimos 30 días)
hamed
hamed el 28 de Mayo de 2018
Comentada: hamed el 28 de Mayo de 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.

Respuesta aceptada

Rik
Rik el 28 de Mayo de 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

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by