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

冷暖自知 提交于 2019-12-19 04:01:47

问题


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?


回答1:


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.)




回答2:


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);



回答3:


x = [1 2 3 4 5]; upsample(x,3)

o/p: 1 0 0 2 0 0 3 0 0 4 0 0 5 0 0

Cheers!!



来源:https://stackoverflow.com/questions/11776251/inserting-variable-number-of-zeros-between-non-zero-elements-in-a-vector-in-matl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!