How can I sort a 2-dimensional array in MATLAB relative to the second row?

I have an array say "a"

a =

 1     4     5
 6     7     2

if I use the function b = sort (a)

gives ans

b =

 1     4     2
 6     7     5

but i want as like

b =

 5     1     4
 2     6     7

the middle 2nd row should be sorted, but the elements of the ist row should remain unchanged and should correspond to row 2.

+3
source share
3 answers

sortrows (a '2)'

Pulling it separately:

a =  1     4     5
     6     7     2

a' = 1 6
     4 7
     5 2

sortrows(a',2) = 5 2
                 1 6
                 4 7

sortrows(a',2)' = 5 1 4
                  2 6 7

The key here is to sort the sorting by the specified line, all the rest follow its order.

+3
source

You can use the SORT function only in the second line, and then use the index output to sort the entire array:

[junk,sortIndex] = sort(a(2,:));
b = a(:,sortIndex);
0

a = [1 4 5; 6 7 2]
a =
     1     4     5
     6     7     2
>> [s,idx] = sort(a(2,:))
s =
     2     6     7
idx =
     3     1     2
>> b = a(:,idx)
b =
     5     1     4
     2     6     7

In other words, you use the second argument sortto get the desired sort order, and then apply it to the whole item.

0
source

Source: https://habr.com/ru/post/1759647/


All Articles