Sort Matrix based on column of another matrix

3 views (last 30 days)
I have matrices A and B
A=[1 1 4; 2 2 5; 3 3 6; 4 4 8; 5 5 9; 6 8 5; 7 9 4; 8 1 2; 9 3 4; 10 4 1];
B=[3;5;7;2;1;8;4;6;9];
I want to sort matrix A using the values in the column matrix B to have the C below:
C=[A=[3 3 6; 5 5 9; 7 9 4; 2 2 5; 1 1 4; 8 1 2; 4 4 8; 6 8 5; 9 3 4]
I have tried the code below, but it seems not to work
q=ismember(A(:,1), B(:,1), 'rows');
z=find(q);
C=A(z,1:3);

Answers (1)

Alex Mcaulley
Alex Mcaulley on 5 Aug 2019
C = A(B,:)
  2 Comments
Christopher Ibeh
Christopher Ibeh on 5 Aug 2019
Thanks but am getting 27 rows instead of 9 rows for C.
Alex Mcaulley
Alex Mcaulley on 5 Aug 2019
Sure?
A = [1 1 4; 2 2 5; 3 3 6; 4 4 8; 5 5 9; 6 8 5; 7 9 4; 8 1 2; 9 3 4; 10 4 1];
B = [3;5;7;2;1;8;4;6;9];
C = A(B,:)
C =
3 3 6
5 5 9
7 9 4
2 2 5
1 1 4
8 1 2
4 4 8
6 8 5
9 3 4

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!