F# Vector Example

← All NMath Code Examples

 

#light

namespace CenterSpace.NMath.Core.Examples.FSharp

open System
open CenterSpace.NMath.Core

module VectorExample =

  /// <summary>
  /// A .NET example in C# showing some of the basic functionality of the vector classes.
  /// </summary>

  let v = new DoubleVector("[1 2 3 4 5 6]")

  // You can obtain different vector "views" of the data in v.
  // For example, vector viewing every other element of v.
  let everyOther = v.[new Range(0, Position.End, 2)]
  printfn "everyOther = %s" (everyOther.ToString()) // [1 3 5]
  printfn ""

  // Remember that this vector is a different views of the data in
  // v. Changing a value in everyOther will change
  // the corresponding value in v.
  everyOther.[1] <- 10.0
  printfn "Value of v[2] == 10 is %A" (v.[2] = 10.0) // True
  printfn ""

  // You can make sure that your data is not being shared with anyone
  // else by invoking the DeepenThisCopy method. This will insure that
  // you have your own private copy of the data and that it occupies
  // contiguous storage.
  v.DeepenThisCopy() |> ignore
  everyOther.[1] <- 100.0
  printfn "Value of v[2] == 100 is %A" (v.[2] = 100.0) // False
  printfn ""

  // The Resize method changes the length of a vector. Values are
  // truncated or padded with zeros as appropriate.
  // First let's save v's original values.
  let vOrig = v.Clone() :?> DoubleVector

  // Now resize v.
  v.Resize(v.Length + 2) |> ignore
  // v will have its original values in the first v.Length-1 elements.
  // The last two elements will be zero.
  let vOrig1 = v.[new Slice(0, vOrig.Length)]
  printfn "values of v preserved during resize is %s" ((vOrig = vOrig1).ToString())
  printfn ""
  printfn "v resized = %s" (v.ToString())
  printfn ""

  // vector dot, or inner, products are available as
  // static methods in the NMathFunctions class.
  let u = new DoubleVector(v.Length, 1.0, 1.0)
  let dp = NMathFunctions.Dot(v, u)
  printfn "The dot product of %s with %s = %A" (v.ToString()) (u.ToString()) dp
  printfn ""

  // There are also functions for computing mean and variance of the numbers in a vector.
  let mean = NMathFunctions.Mean(v)
  let var = NMathFunctions.Variance(v)
  printfn "The mean of v is %A, and the variance is %A" mean var
  printfn ""

  printfn "Press Enter Key"
  Console.Read() |> ignore 

← All NMath Code Examples
Top