MATLAB: Copy the first n elements of a vector, then skip n elements, then copy the next n elements

Vector x is 2000-by-1

I would like to take the first 20 elements of vector x and copy them to vector y, then copy the next 20 elements of vector x to vector z, then copy the next 20 elements to vector y, and so on.

I understand I could do this with a loop, but am hoping to find a more efficient method.

Upvotes: 1

Views: 379

Answers (1)

Aki Suihkonen
Aki Suihkonen

Reputation: 20037

This can be achieved by reshaping the vector to a matrix, selecting odd/even columns and finally flattening the matrix:

 m = reshape(a, 20, []);
 x = m(:,1:2:end); x = x(:);
 z = m(:,2:2:end); z = z(:);

Upvotes: 4

Related Questions