Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In my experience, when working with arrays (2D and/or matrix) I found that working with arrays internally is often the fastest way to go.</p> <p>For example, combining Daniel's and Ankur's approaches in a mutable way:</p> <pre><code>let mutableSortByCol f (m:Matrix&lt;'T&gt;) = let columns = [| for c in 0 .. m.NumCols - 1 -&gt; m.Column c |&gt; Vector.Generic.toArray |] for c in 0 .. m.NumCols - 1 do columns.[c] |&gt; Array.sortInPlaceBy f Matrix.Generic.init (m.NumRows) (m.NumCols) (fun r c -&gt; columns.[c].[r]) </code></pre> <p>I converted the matrix to an array of columns ('a[][], not 'a[,]), and performed an in-place sort on each column. After that, I filled a new matrix with the sorted result. Note that the original matrix remains unmodified: the columns array is populated with copies of the column vectors (Vector.toArray creates a new array).</p> <p>This approach is faster because it needs no transposes, sorts columns in place, and needs no conversion to and from intermediate list structures by keeping everything array-oriented. I suspect it could be made even faster if the Matrix module supported conversion to/from 'a[][] as well, although it's perhaps not really suited for matrices.</p> <p>Also, in case you didn't know: you can make use of F#'s structural comparison of tuples to sort by second element descending, first element ascending:</p> <p>Example:</p> <pre><code>&gt; mutableSortByCol (fun (a,b) -&gt; (-b,a)) M;; val it : Matrix&lt;float * float&gt; = matrix [[(1.0, 145.0); (1.0, 45.0); (3.0, 145.0); (3.0, 45.0); (5.0, 145.0)] [(3.0, 130.0); (2.0, 45.0); (1.0, 130.0); (4.0, 45.0); (1.0, 130.0)] [(5.0, 130.0); (3.0, 30.0); (5.0, 130.0); (1.0, 30.0); (3.0, 130.0)] [(2.0, 45.0); (4.0, 30.0); (4.0, 45.0); (2.0, 30.0); (2.0, 30.0)] [(4.0, 30.0); (5.0, 30.0); (2.0, 30.0); (5.0, 30.0); (4.0, 30.0)]] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload