how to interchange the elements of a vector/matrix?

hi
a,b,c,d all are 2x1 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.

3 Commenti

It is quite easy to do that. But you have not specified how the data in a,b,c and d are present. Because to get the desired output in each iteration, the number of elements in:
'a' should be 1,
'b' should be 2,
'c' should be 4,
'd' should be 8.
Please specify the format of input data. How a,b,c and d are fed as input to the program? Are they all present in a matrix? Or individual vectors?
hi,
i will run a function and the function will output
for i=1 a 2x1 matrix
for i=2, a 2x2 matrix
for i=3, a 2x3 matrix
for i=4, a 2x4 matrix.
and then i would like to rearrange the columns of the matrices as mentioned in the original post.
a,b,c,d are all basically the outputs of the function.
for better understanding, i have denoted them different name so that i could explain how i want them to be rearranged.
basically i run run a function in a loop.
for i=1, function_output=[a11; a21], rearrange_output=[a11; a21]
for i=2, function_output=[b11 b12;b21 b22], rearrange_output=[b11 a11 b12; b21 a21 b22]
for i=3, function_output=[c11 c12 c13 c14;c21 c22 c23 c24], rearrange_output=[c11 b11 c12 a11 c13 b12 c14; c21 b21 c22 a21 c23 b22 c24]
and so on and so forth.

Accedi per commentare.

 Risposta accettata

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

1 Commento

I agree with @Stephen, this will work in your case @Muhammad Ridwanur Rahim

Accedi per commentare.

Più risposte (0)

Categorie

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by