Rearranging second matrix based on the order of first matrix
2 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!