Flattening/Reshaping 一个密集矩阵

Flattening/Reshaping a DenseMatrix

有没有一种简洁的方法来展平矩阵?

// Install-Package MathNet.Numerics
// Install-Package MathNet.Numerics.FSharp
// Compile to move the .dlls to the bin/debug area

#r @"bin/Debug/MathNet.Numerics.dll"
#r @"bin/Debug/MathNet.Numerics.FSharp.dll"

open System
open MathNet.Numerics
open MathNet.Numerics.LinearAlgebra
open MathNet.Numerics.LinearAlgebra.Double
open MathNet.Numerics.Distributions

let X = DenseMatrix.init 10 2 (fun i j -> Normal.Sample(0., 1.))

X
|> Matrix.toColSeq
|> Seq.concat
|> DenseVector.ofSeq
|> DenseMatrix.OfRowVectors

或者更像是 Matlab 中的 reshape 命令?

需要更多测试。此解决方案仅适用于等级 2。

// 

// Install-Package MathNet.Numerics
// Install-Package MathNet.Numerics.FSharp
// Compile to move the .dlls to the bin/debug area

#r @"bin/Debug/MathNet.Numerics.dll"
#r @"bin/Debug/MathNet.Numerics.FSharp.dll"

open MathNet.Numerics.LinearAlgebra
open MathNet.Numerics.Distributions

// let X = DenseMatrix.init 10 2 (fun i j -> Normal.Sample(0., 1.))
let X = DenseMatrix.init 10 2 (fun i j -> float <| j+(i*2))  // a simple count for testing purposes

let xmod x y = x % y
let xdiv x y = x / y

let reshape2 ci cj (M:Matrix<'m>) =
  let cm,cn = M.RowCount,M.ColumnCount
  let maxix = cm*cn
  DenseMatrix.init ci cj (fun i j->
    let k = xmod (j + (i * ci)) maxix
    let m,n = (xdiv k cn),(xmod k cn)
    M.[m,n]
    )

reshape2 3 3 X     // smaller

reshape2 10 3 X    // larger

reshape2 2 10 X    // same number of elements

注意。这取决于您决定如何处理边缘情况。重复是为更大的目的地定义的。我们为较小的目的地丢弃额外的元素。一种名为 J 的 vector/array 语言可以像这样处理 reshape 请求,对于 rank-n,很好 -- http://www.jsoftware.com/help/dictionary/d210.htm