MATLAB: How to interchange the elements of a vector/matrix

elementsmatrix

hi
a,b,c,d all are 2×1 matrices.
i will run a for loop and with each loop the elements of matrix x will increase.
example-
for i=1, x=[a1]
for i=2, x=[a1 b1 b2]
for i=3, x=[a1 b1 b2 c1 c2 c3 c4]
for i=3 x=[a1 b1 b2 c1 c2 c3 c4 d1 d2 d3 d4 d5 d6 d7 d8]
now after i=2, i want to rearrange the matrix to look like
y=[b1 a1 b2].
after i=3, i want to rearrange the matrix to look like
y=[c1 b1 c2 a1 c3 b2 c4]
after i=4, i want to rearrange the matrix to look like
y= [d1 c1 d2 b1 d3 c2 d4 a1 d5 c3 d6 b2 d7 c4 d8].
please tell me how i can do this?
basically all the new elements will be placed in between the existing elements.

Best Answer

This works:
for k = 1:4
% fake data:
new = zeros(2,pow2(k-1));
new(:) = 10*k+(1:numel(new));
% zip data together:
if k==1
out = new
else
out = [reshape([new(:,1:end-1);out],2,[]),new(:,end)]
end
end
It displays this in the command window:
out =
11
12
out =
21 11 23
22 12 24
out =
31 21 33 11 35 23 37
32 22 34 12 36 24 38
out =
41 31 43 21 45 33 47 11 49 35 51 23 53 37 55
42 32 44 22 46 34 48 12 50 36 52 24 54 38 56