在Math.Net线性代数中,您可以编写扩展,允许您使用非常好的切片表示法:
// Open Math.NET namespaces (you need MathNet.Numerics package)
open MathNet.Numerics
open MathNet.Numerics.FSharp
open MathNet.Numerics.LinearAlgebra.Double
// Define type extension for 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)
// Define type extension for the generic matrix type
type MathNet.Numerics.LinearAlgebra.Generic.
Matrix<'T when 'T : struct and 'T : (new : unit -> 'T)
and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable
and 'T :> System.ValueType> with
// Implement slicing for matrices (using rows & columns)
member x.GetSlice(rstart, rfinish, cstart, cfinish) =
let cstart = defaultArg cstart 0
let rstart = defaultArg rstart 0
let cfinish = defaultArg cfinish (x.ColumnCount - 1)
let rfinish = defaultArg rfinish (x.RowCount - 1)
x.SubMatrix(rstart, rfinish - rstart + 1, cstart, cfinish - cstart + 1)
然后拍摄切片很容易
// 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]
// Example: Get some slices from a matrix
let m = matrix [ [ 1.0; 2.0; 3.0 ]
[ 4.0; 5.0; 6.0 ] ]
m.[0 .. 1, 0 .. 1] // get first square 2x2
m.[0 .. 1, 2 ..] // get the last column
m.[1 .., 0 .. 2] // get the last row
我需要从矢量构建矩阵,并以这种方式切片可能是最有效的方法。让我解释一下:
您将获得一个说明q
长度观测值的列向量,最新观察值为最高值x(t)
,第q个观测值为最低值x(t - q)
。因此,矩阵的第一列从x(t)
变为x(t-q)
。您还会获得一个数字n
,以便矩阵中的第一行为x(t)
,x(t-1)
,...,x(t-n)
,第二行为x(t-1)
},x(t-2)
,...,x(t-n-1)
等,直到最后一个元素为x(t-q-n)
的行。
所以你留下q
列的n
行的三角矩阵。
C#中用于切割Math.Net线性代数向量的上述F#函数的等效版本是什么?