roni
roni

Reputation: 1454

sort multiple columns according to particular order

I have a matrix

A = 1   1   1
    2   2   2
    3   3   3
    4   4   4 
    5   5   5

I have 3 arrays containing the orders in which I separately want to sort the respective columns. Example I1 for column 1, I2 for column 2, ....

I1 = 5   I2 = 4   I3 = 3
     4        3        2 
     3        2        1
     2        1        5
     1        5        4

After sorting the matrix A I should get:- If only I1 is used to sort the 1st column

A = 5   1   1
    4   2   2
    3   3   3
    2   4   4 
    1   5   5

If only I2 is used to sort the 2nd column

A = 1   4   1
    2   3   2
    3   2   3
    4   1   4 
    5   5   5

If only I3 is used to sort the 3rd column

A = 1   1   3
    2   2   2
    3   3   1
    4   4   5 
    5   5   4

If only I1,I2,I3 is used to sort the all columns

A = 5   4   3
    4   3   2
    3   2   1
    2   1   5 
    1   5   4

Please suggest me how to do.

Upvotes: 0

Views: 76

Answers (1)

Hugh Nolan
Hugh Nolan

Reputation: 2519

If their dimensions are all the same, this should be what you need:

A([I1 I2 I3]);

If you wish to sort columns individually, you can use this syntax:

A(:,2)=A(I2,2);

Or e.g. columns 2 and 3:

A(:,[2 3]) = [A(I2,2) A(I3,3)];

Upvotes: 2

Related Questions