Taking alternately elements of two vectors and composing them at Matlab

advertisements

This question already has an answer here:

  • Interweaving vectors 5 answers

Could you help me to write down a very fast algorithm in Matlab that does the following: I have 2 vectors, A of dimension nx1 and B of dimension nx1. I want to construct C of dimension 2nx1 such that

C(1)=A(1), C(2)=B(1), C(3)=A(2), C(4)=B(2), C(5)=A(3), C(6)=B(3), ...

I though about

C=[];
for j=1:n
    C=[C; [A(j) B(j)]'];
end

Do you know something faster and more efficient?

Example:

n=9
A=[1 3 5 7 9 11 13 15 17]';
B=[2 4 6 8 10 12 14 16 18]';
C=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18]';


In matlab, index operations are generally faster than for-loops.
What I would do is first construct a 2nx1 matrix and then use indexing to assign the values:

C = zeros(2*n,1);
C(1:2:end) = A;
C(2:2:end) = B;