Search code examples
matlabvectorzero

Inserting variable number of zeros between non-zero elements in a vector in MATLAB


I have a vector like:

a = [1,2,3,4,5,6...,n]

and I would like to obtain a new vector like this:

a_new = [1,0,0,2,0,0,3,0,0,4,0,0,5,0,0,6,...,0,0,n]

where a fixed number of zeros (2 in the above example) are inserted between the non-zero elements. If I choose zero_p=3, the new vector would be:

a_new = [1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0,5,0,0,0,6,...,0,0,0,n]

etc.

How can I do this?


Solution

  • Try this:

    zero_p=3;
    a_new=zeros(1, (zero_p+1)*length(a)-zero_p);
    a_new(1:(zero_p+1):end)=a;
    

    (Untested, but should hopefully work.)