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
There's a few ways I can think of:
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
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);
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);
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!!
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.)