Reputation: 863
I want to link, join and sort two arrays that are linked to another two arrays, like so:
A1 = [5, 4, 8, 6]
linked to
A2 =[10, 15, 12, 14]
and
B1= [5.5, 6.5, 8.5, 4.5]
linked to
B2=[11.5, 25.5, 16.5, 49.5]
I want to join A1 with B1 into C1 and A2 with B2 into C2 and when I sort C1, C2's numbers should move with the numbers of C1, since they are linked. More clearly:
C1=[5, 4, 8, 6, 5.5, 6.5, 8.5, 4.5]
C2=[10, 15, 12, 14, 11.5, 25.5, 16.5, 49.5]
D1=[4, 4.5, 5, 5.5, 6, 6.5, 8, 8.5 ] % sorted C1
D2 = [15, 49.5, 10, 11.5, 14, 25.5, 12, 16.5 ] % since 4 is linked to 15, 4.5 is linked to 49.5 etc...
I am actually trying to do in matlab what is very simple in excel, you have two columns, sort one and the other follows.
Here's what I tried so far:
C1=[A1, B1];%join them
C2=[A2, B2];
D=[C1;C2];
D1=sort(D(1,:)); % this does not work
I think I have to use find somewhere, but I don't know how.
Upvotes: 1
Views: 56
Reputation: 18905
Using sort
was the right idea. You can obtain the indices of the sorted array by getting the second return value, see the documentation on sort
.
So, the quite simple solution should be:
D = [C1; C2]; % Build D
[~, idx] = sort(C1); % Sort C1, but only use the indices of the sorted C1
D = D(:, idx) % Rearrange D column-wise by the sorted indices
D =
4.0000 4.5000 5.0000 5.5000 6.0000 6.5000 8.0000 8.5000
15.0000 49.5000 10.0000 11.5000 14.0000 25.5000 12.0000 16.5000
Upvotes: 3