Henry
Henry

Reputation: 171

Interleave and Deinterleave a vector into two new vectors

Interleaver: Assume we have vector X= randi(1,N) I would like to split the contents of X into two new vectors X1and X2 such that the first element of X is the first element of X1, the first element of X2 is the second element of X, the third element of X is the second element of X1 and the fourth element of X is the second element of X2... etc till the last element of the vector `X.

I have the following idea

X1(1)=X(1);
X2(1)=X(2);


for i=1:length(X)
X1(i)= X(i+2);
end
for j=2:length (X)
X2(i)= X(i+2)
end

My question is: is my method correct? is there a better way to do it?

Deinterleaver I also have the reverse problem so basically in this case I have X1 and X2 and would like to recover X, how would I efficiently recover X?

Upvotes: 1

Views: 1366

Answers (4)

gnovice
gnovice

Reputation: 125854

Just to add another option, you could use the deal function and some precomputed indices. This is basically the same as the answer from Peter M, but collecting the assignments into single lines:

X = randi(10, [1 20]);  % Sample data
ind1 = 1:2:numel(X);    % Indices for x1
ind2 = 2:2:numel(X);    % Indices for x2

[x1, x2] = deal(X(ind1), X(ind2));  % Unweave (i.e. deinterleave)

[X(ind1), X(ind2)] = deal(x1, x2);  % Interleave

Upvotes: 1

Cris Luengo
Cris Luengo

Reputation: 60444

I think the terminology in this question is reversed. Interleaving would be to merge two vectors alternating their values:

x1 = 10:10:100;
x2 = 1:1:10;
x = [x1;x2];
x = x(:).';

This is the same as the one-liner:

x = reshape([x1;x2],[],1).';

Deinterleaving would be to separate the interleaved data, as already suggested by David in a comment and Tom in an answer:

y1 = x(1:2:end);
y2 = x(2:2:end);

but can also be done in many other ways, for example inverting the process we followed above:

y = reshape(x,2,[]);
y1 = y(1,:);
y2 = y(2,:);

To verify:

isequal(x1,y1)
isequal(x2,y2)

Upvotes: 5

Peter M
Peter M

Reputation: 1988

I was hoping, as well for some cool new one liner, but anyway, following the previous answer you can use the same indexing expression for the assignment.

x  = 1:20
x1 = x(1:2:end)
x2 = x(2:2:end)
y = zeros(20,1)
y(1:2:end) = x1
y(2:2:end) = x2

Upvotes: 2

Tom
Tom

Reputation: 2704

I think it's hard to get a cleaner solution than this:

x  = 1:20
x1 = x(1:2:end)
x2 = x(2:2:end)

Upvotes: 1

Related Questions