MATLAB Answers

# Sort a matrix with another matrix

83 views (last 30 days)
Bi on 16 Oct 2017
Commented: Andrei Bobrov on 29 Apr 2019
How can I sort a matrix A with another matrix B, where the elements of B may be replicated (not in a complete sequence of 1:n with all numbers of 1,2,3,...,n-1,n)? For example,
If I have a matrix A=[5 1; 8 2; 7 3; 3 4; 2 5];
and a matrix of B=[0; 0; 2; 1; 1];
(Or a matrix of B1 where B1=[0 0; 0 0; 2 2; 1 1; 1 1];)
How can I sort A with B with answer of resultant matrix C of C=[5 1; 8 2; 2 5; 3 4; 7 3];?
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Azzi Abdelmalek on 16 Oct 2017
[~,id]=sort(B)
C=A(id,:)
##### 2 CommentsShowHide 1 older comment
Walter Roberson on 27 Jul 2018

Sign in to comment.

### More Answers (1)

Andrei Bobrov on 16 Oct 2017
[~,ii] = sortrows([B,A(:,1)])
C = A(ii,:)
##### 2 CommentsShowHide 1 older comment
Andrei Bobrov on 29 Apr 2019
[~,i1] = sort(A);
[~,i2] = sort(i1);
Bst = sort(B);
C = Bst(i2);

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!