0
votes

I want to sort in Matlab the element of each row of a matrix A in a matrix B and obtain a matrix C reporting the column index of each sorted element in the original matrix A. If two elements of a row of A are the same the reported column indices should be in increasing order, e.g.

A=[3 2 1 4; 5 6 7 8; 9 0 10 2; 2 1 1 0]
B=[1 2 3 4; 5 6 7 8; 0 2 9 10; 0 1 1 2]
C=[3 2 1 4; 1 2 3 4; 2 4 1 3; 4 2 3 1]
1

1 Answers

2
votes

The builtin sort function will do this, when ran on rows (dimension 2 in Matlab).

First output will be the elements sorted within each row giving B
Second output will be the column indices of the elements of B from A within each row giving C

[B,C]=sort(A,2)

or if you just want C replace B with ~ in the above line..