I recently had the same question and used some of edkeveked's answer to come up with these two functions. They look awkward (and probably one can improve on the performance) but they get the job done for a 2D-matrix.
const sortRows = (matrix, asc = true) => {
return tf.tidy(() => {
const vector = matrix.reshape([-1])
const topk = tf.topk(matrix, matrix.shape[1]).indices
const inds = tf.add(topk, tf.range(0, matrix.shape[0] * matrix.shape[1], matrix.shape[1], 'int32').mul(tf.ones([matrix.shape[1], matrix.shape[0]])).transpose()).reshape([-1]).cast("int32")
const sorted = vector.gather(inds).reshape(matrix.shape)
return asc ? sorted.reverse(1) : sorted
})
}
const sortColumns = (matrix, asc = true) => sortRows(matrix.transpose(), asc).transpose()
Running the following commands
m = tf.tensor([[1, 2, 3], [3, 2, 1], [3, 5, 4], [-2, 1, 6]])
sortColumns(m).print()
will give you
Tensor
[[-2, 1, 1],
[1 , 2, 3],
[3 , 2, 4],
[3 , 5, 6]]