0
votes

I have an array called A, it has 2 Rows and 56 columns ( as shown in the attached image)

array

the first row represents the values while the second row represents the index for each value.

I want to sort the first row but keep the index for each value (I tried to use Sort function but it doesnt keep the index of each value in the second row). for example, let's suppose I have this matrix

input x=[9 2 4 3 ;3 1 8 2 ]

i want the output looks like this y=[2 3 4 9; 1 2 8 3 ];

3
you can use sortrows: y=sortrows(x')' - Adiel
@Adiel sortrows generates wrong result. You can test this x=[1 1 1 2 2 3;1 2 1 4 7 1] - rahnema1
What the problem with the output of your example? In which manner you consider it "wrong"? Doesn't seem that the OP wants to preserve some original order, or he has any preference to order of duplicate values, especially while it can't be defined "wrong", just a specific case dependent. - Adiel

3 Answers

1
votes

There are a couple of ways to achieve this:

[y1,I] = sort(x(1,:))

y2 = x(2,I)

y = [ y1 ; y2 ]

This basically sort the first row of your data, and save the sorting index in I, and then use those index to get the 'sorted' second row, and then just join them

or

y = sortrows(x')'

The ' operator transposes the matrix, which allows you to use sortrows and then use it again to reshape your output matrix.

1
votes

You can use indices of sorted elements

[S,I]=sort(x(1,:));
result = [S;x(2,I)]

The first row is sorted and indices of the sorted elements is used to order the second row.

result

2   3   4   9
1   2   8   3
0
votes

You can get the indices directly from sorting the first row. These can be used as an argument in x itself:

x=[9 2 4 3 ;3 1 8 2 ];

%get the indices of the first row:
[~,indices] = sort(x(1,:))

%return x in the order "indices" for each row: 
y = [x(1,indices);x(2,indices)]