展平/重塑DenseMatrix

时间:2017-05-10 23:00:29

标签: f# mathnet

是否有简洁的方法来压平矩阵?

// 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命令?

1 个答案:

答案 0 :(得分:3)

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

// http://stackoverflow.com/questions/43903949/flattening-reshaping-a-densematrix/43904614#43904614

// 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

NB。这取决于您决定如何处理边缘情况。为更大的目的地定义重复。我们为较小的目的地丢弃额外的元素一个名为J的矢量/数组语言处理这样的重塑请求,对于rank-n,很好 - http://www.jsoftware.com/help/dictionary/d210.htm