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

后端 未结 3 1712
慢半拍i
慢半拍i 2021-01-06 13:31

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         


        
3条回答
  •  醉梦人生
    2021-01-06 13:34

    There's a few ways I can think of:

    Kronecker product

    The kronecker product is excellently suited for this. In Matlab, kron is what you're looking for:

    a = 1:4;
    a = kron(a, [1 0 0])
    
    ans = 
    
        1     0     0     2     0     0     3     0     0     4     0     0    
    

    or, generalized,

    a = 1:4;
    zero_p = 3;
    b = [1 zeros(1,zero_p-1)];
    a = kron(a, b)
    
    ans = 
    
        1     0     0     2     0     0     3     0     0     4     0     0     
    

    If you want to have it end with a non-zero element, you have to do one additional step:

    a = a(1:end-zero_p);
    

    Or, if you like one-liners, the whole thing can be done like this:

    a = 1:4;
    zero_p = 3;
    a = [kron(a(1:end-1), [1 zeros(1,zero_p-1)]), a(end)]
    
    ans = 
    
       1     0     0     2     0     0     3     0     0     4
    

    Zero padding

    Probably the simplest method and best performance:

     a = 1:4;
     zero_p = 3;
     a = [a; zeros(zero_p, size(a, 2))];
     a = a(1:end-zero_p);
    

    Matrix multiplication

    Also simple, readable and great performance, although it might be overkill for many situations other than this particular scenario:

    a = 1:4;
    b = [1; zeros(zero_p, 1)];
    a = b*a;
    a = a(1:end-zero_p);
    

提交回复
热议问题