Reputation: 233
I have a vector A = 1:2*N
. I want to rearrange its elements into another vector like this:
B = [A(1:2), A(N+1:N+2), A(3:4), A(N+3:N+4), ..., A(N-1:N), A(2*N-1:2*N)];
How can I implement this in Matlab most efficiently? without a loop?
Upvotes: 2
Views: 67
Reputation: 45752
The following will work when N
is even:
N = 4;
A = 1:2*N;
temp = permute(reshape(A,2,[],2), [1,3,2]);
B = temp(:)'
if N
can be odd, I guess you could pad A
with two NaN
s and then remove the last two elements from B
at the end? i.e. A(end+1:end+2) = NaN
at the beginning and then B = B(1:end-2)
at the end
Upvotes: 2