user2887210
user2887210

Reputation: 35

Insert new values into an array

I currently have a column vectors of different lengths and I want to insert another column vector at various points of the original array. i.e. I want to add my new array to the start of the old array skip 10 places add my new array again, skip another 10 spaces and add my new array again and so on till the end of the array. I can do this by using:

OffsetSign = [1:30]';
Extra = [0;0;0;0;0];
OffsetSign =[Extra;OffsetSign(1:10);Extra;OffsetSign(11:20);Extra;OffsetSign(21:30)];

However this is not suitable for longer arrays. Any tips on an easy way to do this for longer arrays?

Upvotes: 1

Views: 295

Answers (1)

bla
bla

Reputation: 26069

here's one way to do it:

a = [1:30]';
b = [0;0;0;0;0];

a=reshape(a,10,[]);
b=repmat(b,[1 size(a,2)])
r=[b ; a]
r=r(:);

the trick is to reshape a to a matrix with columns of the right size (10 elements each). Replicate b to this # of columns , concatenate both and flatten the matrix to a vector...

Upvotes: 4

Related Questions