Interleave and Deinterleave a vector into two new vectors

前端 未结 4 685
遇见更好的自我
遇见更好的自我 2021-01-16 08:17

Interleaver: Assume we have vector X= randi(1,N) I would like to split the contents of X into two new vectors X1and <

相关标签:
4条回答
  • 2021-01-16 08:40

    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
    
    0 讨论(0)
  • 2021-01-16 08:42

    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)
    
    0 讨论(0)
  • 2021-01-16 08:48

    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
    
    0 讨论(0)
  • 2021-01-16 08:51

    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)
    
    0 讨论(0)
提交回复
热议问题