9 people like it.
Like the snippet!
Slicing for Math.Net vectors and matrices
This snippet adds the 'GetSlice' operation to Math.Net vector and matrix types. This makes it possible to get sub-vectors and sub-matrices using the convenient syntax (For vectors 'vect.[start .. end]` or 'vect.[start ..]' and for matrices 'mat.[r1 .. r2, c1 .. c2]' and similar).
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
|
// Open Math.NET namespaces (you need MathNet.Numerics package)
open MathNet.Numerics
open MathNet.Numerics.FSharp
open MathNet.Numerics.LinearAlgebra.Double
// Define type extension ofr the generic vector type
// (Here we need to repeat all constraints, so it is a bit ugly)
type MathNet.Numerics.LinearAlgebra.Generic.
Vector<'T when 'T : struct and 'T : (new : unit -> 'T)
and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable
and 'T :> System.ValueType> with
/// Implements slicing of vector - both arguments are option types
member x.GetSlice(start, finish) =
let start = defaultArg start 0
let finish = defaultArg finish (x.Count - 1)
x.SubVector(start, finish - start + 1)
// Example: Get some slices from a vector
let v = vector [ 1.0; 2.0; 3.0 ]
v.[0 .. 1] // elements [1.0; 2.0]
v.[1 ..] // elements [2.0; 3.0]
v.[.. 1] // elements [1.0; 2.0]
|
namespace MathNet
namespace MathNet.Numerics
namespace Microsoft.FSharp
namespace MathNet.Numerics.LinearAlgebra
namespace MathNet.Numerics.LinearAlgebra.Double
type Vector =
inherit Vector<float>
member AbsoluteMaximum : unit -> float
member AbsoluteMaximumIndex : unit -> int
member AbsoluteMinimum : unit -> float
member AbsoluteMinimumIndex : unit -> int
member CoerceZero : threshold:float -> unit
member InfinityNorm : unit -> float
member L1Norm : unit -> float
member L2Norm : unit -> float
member MaximumIndex : unit -> int
member MinimumIndex : unit -> int
...
Full name: MathNet.Numerics.LinearAlgebra.Double.Vector
type unit = Unit
Full name: Microsoft.FSharp.Core.unit
namespace System
type IEquatable<'T> =
member Equals : other:'T -> bool
Full name: System.IEquatable<_>
type IFormattable =
member ToString : format:string * formatProvider:IFormatProvider -> string
Full name: System.IFormattable
type ValueType =
member Equals : obj:obj -> bool
member GetHashCode : unit -> int
member ToString : unit -> string
Full name: System.ValueType
val defaultArg : arg:'T option -> defaultValue:'T -> 'T
Full name: Microsoft.FSharp.Core.Operators.defaultArg
val v : obj
Full name: Script.v
More information