Sorting a matrix according to another one
1 view (last 30 days)
Show older comments
Mattia Salomone
on 31 May 2023
Commented: Mattia Salomone
on 1 Jun 2023
Dear all,
I have the following problem to solve.
clear
clc
% A matrix defined as follows
A=[11 0.001 3
11 0.001 4
12 0.003 5
9 0.002 6
8 0.000 7
10 0.004 8
8 0.000 9
9 0.002 10];
% B matrix is the reference one
B=[8 0.000
8 0.000
9 0.002
10 0.004
9 0.002
11 0.001
11 0.001
12 0.003];
I want to sort A such that the first two columns coincide with B (and sort the other A column in agreement with this, of course). I used this code, but the problem is that since in B I have repeted conditions the result is not the one I desire.
[~,Y]=ismember(A(:,1:2),B,'rows');
[~,Z]=sort(Y);
C=A(Z,:);
% C=8 0.000 7
% 8 0.000 9
% 9 0.002 6
% 9 0.002 10
% 10 0.004 8
% 11 0.001 3
% 11 0.001 4
% 12 0.003 5
But what I want is
% C=8 0.000 7
% 8 0.000 9
% 9 0.002 6
% 10 0.004 8
% 9 0.002 10
% 11 0.001 3
% 11 0.001 4
% 12 0.003 5
Do you have any suggestions that don't involve using nested loops and if conditions?
Thank you very much for your attention!
Mattia
2 Comments
Accepted Answer
Torsten
on 31 May 2023
Edited: Torsten
on 31 May 2023
A = [11 0.001 3
11 0.001 4
12 0.003 5
9 0.002 6
8 0.000 7
10 0.004 8
8 0.000 9
9 0.002 10];
% B matrix is the reference one
B = [8 0.000
8 0.000
9 0.002
10 0.004
9 0.002
11 0.001
11 0.001
12 0.003];
[~,idx] = sortrows(A,[1 2]);
[~,jdx] = sortrows(B,[1 2]);
C = A(idx(jdx),:)
3 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!