How to rearrange rows in specific intervals

I have a matrix like so:
[x1 y1 z1;
x2 y2 z2;
x3 y3 z3;
x1 y1 z1;
x2 y2 z2;
x3 y3 z3;
x1 y1 z1;
x2 y2 z2;
x3 y3 z3]
Is there a non-loop solution to reorder the matrix to:
[x1 y1 z1;
x1 y1 z1;
x1 y1 z1;
x2 y2 z2;
x2 y2 z2;
x2 y2 z2;
x3 y3 z3;
x3 y3 z3;
x3 y3 z3]
In other words get every third column (in this case) and set them in order. The final matrix would end up being the same size.
I appreciate any help possible.

 Réponse acceptée

Star Strider
Star Strider le 5 Déc 2017
I use the Symbolic Math Toolbox to illustrate the approach and the desired result:
syms x1 y1 z1 x2 y2 z2 x3 y3 z3 real
M = [x1 y1 z1;
x2 y2 z2;
x3 y3 z3;
x1 y1 z1;
x2 y2 z2;
x3 y3 z3;
x1 y1 z1;
x2 y2 z2;
x3 y3 z3];
A = reshape(M, 3, 3, []);
B = permute(A, [3 2 1]);
Result = reshape(B, 3, [])'
Result =
[ x1, y1, z1]
[ x1, y1, z1]
[ x1, y1, z1]
[ x2, y2, z2]
[ x2, y2, z2]
[ x2, y2, z2]
[ x3, y3, z3]
[ x3, y3, z3]
[ x3, y3, z3]

Plus de réponses (1)

KSSV
KSSV le 5 Déc 2017
A = [1 2 3 ; 4 5 6 ; 7 8 9 ; 1 2 3 ; 4 5 6 ;7 8 9 ; 1 2 3 ; 4 5 6 ; 7 8 9] ;
[val,idx] = sort(A(:,1)) ;
B = A(idx,:)

2 commentaires

Alejandro
Alejandro le 5 Déc 2017
What if the values of the matrix are not in order? suppose a random matrix.
KSSV
KSSV le 5 Déc 2017
Modifié(e) : KSSV le 5 Déc 2017
Same thing works.......provided the random matrix is given in the way the matrix is.
x1 = rand ; y1 = rand ;z1 = rand ;
x2 = rand ; y2 = rand ;z2 = rand ;
x3 = rand ; y3 = rand ;z3 = rand ;
A = [x1 y1 z1; x2 y2 z2; x3 y3 z3; x1 y1 z1; x2 y2 z2; x3 y3 z3; x1 y1 z1; x2 y2 z2; x3 y3 z3] ;
[val,idx] = sort(A(:,1)) ;
B = A(idx,:)

Connectez-vous pour commenter.

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by