Julia: Sort the columns of a matrix by the values in another vector (in place...)?
<p>I am interested in sorting the columns of a matrix in terms of the values in 2 other vectors. As an example, suppose the matrix and vectors look like this:</p>

<pre><code>M  = [ 1   2   3   4   5   6  ; 
       7   8   9   10  11  12 ; 
       13  14  15  16  17  18 ]

v1 = [ 2 , 6 , 6 , 1 , 3 , 2  ]
v2 = [ 3 , 1 , 2 , 7 , 9 , 1  ]
</code></pre>

<p>I want to sort the columns of <code>A</code> in terms of their corresponding values in <code>v1</code> and <code>v2</code>, with <code>v1</code> taking precedence over <code>v2</code>. Additionally, I am interested in trying to sort the matrix <strong>in place</strong> as the matrices I am working with are very large. Currently, my crude solution looks like this:</p>

<pre><code>MM = [ v1' ; v2' ; M ] ; ## concatenate the vectors with the matrix
MM[:,:] = sortcols(MM , by=x-&gt;(x[1],x[2])) 
M[:,:] = MM[3:end,:]
</code></pre>

<p>which gives the desired result:</p>

<pre><code>3x6 Array{Int64,2}:
  4   6   1   5   2   3
 10  12   7  11   8   9
 16  18  13  17  14  15
</code></pre>

<p>Clearly my approach is not ideal is it requires computing and storing intermediate matrices. Is there a more efficient/elegant approach for sorting the columns of a matrix in terms of 2 other vectors? And can it be done <strong>in place</strong> to save memory? </p>

<p>Previously I have used <code>sortperm</code> for sorting an array in terms of the values stored in another vector. Is it possible to use <code>sortperm</code> with 2 vectors (and in-place)?</p>