0

Is there a concise way to flatten a matrix?

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

Or more preferably something like the reshape command in Matlab?

sgtz
  • 8,849
  • 9
  • 51
  • 91

1 Answers1

3

more testing required. This solution is for rank 2, only.

// 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. It depends on how you decide to handle the edge cases. Repetition is defined for larger destinations. We drop extra elements for smaller destinations. A vector/array language called J handles reshape requests like this, for rank-n, nicely -- http://www.jsoftware.com/help/dictionary/d210.htm

sgtz
  • 8,849
  • 9
  • 51
  • 91
  • 1
    I'll look into it further but something is off. Seems like it shuffles the data. – professor bigglesworth May 11 '17 at 13:47
  • 1
    @professorbigglesworth: you were right. Correction made. Also, I changed the DenseMatrix to a count rather than a random distribution. Is this row-wise reshape definition the one you were looking for? I haven't used MatLab for a while. ty. – sgtz May 12 '17 at 07:52