Asked by Hollis Williams
on 19 May 2019

I have a 1x300 vector and would like to make it into a 1x400 vector by inserting a 0 after every third element, a 0 after every sixth element and a 1 after the ninth element and then after the twelfth element insert a 0 and repeat the pattern.

So for example if I have

0 0 1 0 1 0 1 0 0

this would become

0 0 1 0 0 1 0 0 1 0 0 1

and so on.

Answer by dpb
on 19 May 2019

Edited by dpb
on 22 May 2019

Accepted Answer

>> v=reshape([reshape(v,[],3),[0 0 1].'].',1,[])

v =

0 0 1 0 0 1 0 0 1 0 0 1

>>

To generalize, repmat the augmentation vector as many times as needed.

>> v=reshape([reshape(v,[],3),repmat([0 0 1].',numel(v)/9,1)].',1,[])

v =

0 0 1 0 0 1 0 0 1 0 0 1

>>

ADDENDUM: To make the generalizaton more clear perhaps...

lenStr=3; % length prior to insertion point

vaug=[0 0 1].'; % the augmenting vector

lenAug=numel(vaug); % length of augmentation vector

v=reshape([reshape(v,[],lenStr),repmat(vaug,numel(v)/(lenStr*lenAug),1)].',1,[])

dpb
on 21 May 2019

Alone, yes. In patterns as you've outlined "not so much" because the positions change with the insertion when you insert after element 3, now 4 is 5 so then you've got to recompute.

That's what the above avoids.

Hollis Williams
on 21 May 2019

dpb
on 21 May 2019

Same logic works with the augmentation vector being only 1 element, too:

reshape([reshape(v,[],3) ones(108/3,1)].',1,[])

You just have to compute the repeat factor correctly dependent upon the length being added--how many rows does it add each time?

The above with the hardcoded '9' was specific for the original question of 3.

Sign in to comment.

Answer by Jos (10584)
on 21 May 2019

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.