MATLAB: Adding Zeroes and Ones into a Vector

MATLABmatrixvector

I have a 1×300 vector and would like to make it into a 1×400 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.

Best 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,[])