Rearranging second matrix based on the order of first matrix

2 views (last 30 days)
I have two matrices A and B with n number of rows and 4 columns. The 2nd and third column of both matrices are same but not the order. I would like to arrange the matrix B with respect to the order of 2nd and third column in matrix A.
A = [ 1 2 3 4.1; 5 12 7 4.1; 9 10 11 4.1];
B = [ 131 10 11 8.1; 21 12 7 8.1; 91 2 3 8.1];
so B sorted should look like,
Bsorted = [91 2 3 8.1; 21 12 7 8.1; 131 10 11 8.1]
Thanks

Accepted Answer

Stephan
Stephan on 19 Jan 2019
Edited: Stephan on 19 Jan 2019
A = [1 2 3 4.1; 5 12 7 4.1; 9 10 11 4.1]
B = [131 10 11 8.1; 21 12 7 8.1; 91 2 3 8.1];
B_new = sortCols2_3(A,B)
function B_new = sortCols2_3(A,B)
[m,n]=meshgrid(1:size(A,1),1:size(A,1));
B1 = reshape(B(m,2:3)==A(n,2:3),size(A,1),[]);
B1 = B1(:,1:size(A,1));
[r,c] = find(B1);
B_new(c,:)=B(r,:);
end
  3 Comments
Stephan
Stephan on 19 Jan 2019
Edited: Stephan on 19 Jan 2019
see my edited answer.
i tried it also with this extended example, it appears to work for me:
A = [1 2 3 4.1; 5 12 7 4.1; 9 10 11 4.1; 11 6 8 21]
B = [1 6 8 1; 131 10 11 8.1; 21 12 7 8.1; 91 2 3 8.1];

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!