From 4dfa1c66a55b0dc06201e82a464f66f9e6336667 Mon Sep 17 00:00:00 2001 From: Gustavo Guerra Date: Sun, 23 Oct 2011 19:12:52 +0100 Subject: [PATCH] Add Vector.insert (similar to Matrix.InsertColumn and Matrix.InsertRow) --- src/FSharp/Vector.fs | 13 ++++++++++++- src/FSharpUnitTests/Program.fs | 2 ++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/FSharp/Vector.fs b/src/FSharp/Vector.fs index e8a08b24..e05a1fe1 100644 --- a/src/FSharp/Vector.fs +++ b/src/FSharp/Vector.fs @@ -32,6 +32,7 @@ namespace MathNet.Numerics.LinearAlgebra.Double open MathNet.Numerics.LinearAlgebra open MathNet.Numerics.LinearAlgebra.Generic + /// A module which implements functional vector operations. module Vector = @@ -173,4 +174,14 @@ module Vector = let mutable p = v.Item(v.Count-1) for i=2 to v.Count do p <- f (v.Item(v.Count - i)) p - p \ No newline at end of file + p + + /// Creates a new vector and inserts the given value at the given index. + let inline insert index value (v: #Vector) = + let newV = new DenseVector(v.Count + 1) + for i = 0 to index - 1 do + newV.Item(i) <- v.Item(i) + newV.Item(index) <- value + for i = index + 1 to v.Count do + newV.Item(i) <- v.Item(i - 1) + newV \ No newline at end of file diff --git a/src/FSharpUnitTests/Program.fs b/src/FSharpUnitTests/Program.fs index 48e6e899..842be081 100644 --- a/src/FSharpUnitTests/Program.fs +++ b/src/FSharpUnitTests/Program.fs @@ -96,6 +96,8 @@ let VectorTests = (Vector.reduce (fun acc x -> acc ** x) smallv |> should approximately_equal 14 0.990295218585507) spec "Vector.reduceBack" (Vector.reduceBack (fun x acc -> x ** acc) smallv |> should approximately_equal 14 0.488911287726319) + spec "Vector.insert" + (Vector.insert 2 0.5 smallv |> should approximately_vector_equal 14 (new DenseVector ( [|0.3;0.3;0.5;0.3;0.3;0.3|] ) :> Vector) ) ]