Thomas
Thomas

Reputation: 543

Zero padding/stuffing in matlab

Basicly I have array like this:

[1 2 3 4 5 6]

I want to have array like this:

[1 0 2 0 3 0 4 0 5 0 6]

So it is L-1 zeros in array where L is the number of all values inside array before zero stuffing.

Anyone have idea how to solve it in Matlab?

Upvotes: 3

Views: 3527

Answers (5)

Aayman Khalid
Aayman Khalid

Reputation: 468

Another way of doing this is:

         a=1:6;
         b=zeros(1,2*length(a)-1);
         j=1;
         for i=1:2:length(b)
             b(i)=a(j);
             j=j+1;
         end

Upvotes: 0

Matti Pastell
Matti Pastell

Reputation: 9283

If you have signal processing toolbox you can use the upsample function:

>> x = 1:5;
>> upsample(x, 2)
ans =
    1     0     2     0     3     0     4     0     5     0

Upvotes: 2

Shai
Shai

Reputation: 114786

Through reshapeing:

a = [1 2 3 4 5 6]; 
b = a; % make copy
b(2,:) = 0; % add zeros
b = b(:)'; %'
b(end) = []; % discard last zero

Upvotes: 1

H.Muster
H.Muster

Reputation: 9317

You can try this:

a = [1 2 3 4 5 6]; 

b = zeros(1, 2 * length(a) - 1);
b(1:2:end) = a;

This results in

b =

     1     0     2     0     3     0     4     0     5     0     6

A shorter version was suggested by Dan in the comments:

b(1:2:2 * length(a) - 1) = a;

Upvotes: 7

am304
am304

Reputation: 13876

Maybe not the most elegant/efficient solution, but the following should work:

x = 1:6;
y = zeros(1,2*length(x)-1);
for k=1:length(x)
    y(2*k-1)=x(k);
end

Arnaud

Upvotes: 0

Related Questions