locked
convert arrays RRS feed

  • Question

  • how to convert one row of a 2D array to a 1D array?

    // Access to first row of array
    let result = my2DArray.[0..0,*]

    //how to convert result to 1D array?



    • Edited by Rainmater Saturday, September 1, 2012 6:27 AM
    Saturday, September 1, 2012 6:26 AM

Answers

  • I'm sure there has to be a simpler way that this, but

    let data = Array2D.create 5 8 0
    let rowIndex = 3 // or whatever
    let row = seq { for i in 0..((Array2D.length2 data)-1) ->  data.[rowIndex,i] } |> Seq.toArray
    does it by the obvious brute-force method.

    • Marked as answer by Rainmater Sunday, September 2, 2012 8:10 AM
    Saturday, September 1, 2012 9:13 AM
  • All the range operations on 2D arrays yield 2D arrays

    > data.[rowIndex..rowIndex, 0..];;
    val it : int [,] = [[0; 0; 0; 0; 0; 0; 0; 0]]

    so at some point you have to do some sequence operation to extract the elements, so you might as well do it straight off.  This is the simplest I've found

    data.[rowIndex..rowIndex, 0..] |> Seq.cast<int> |> Seq.toArray;;
    where 0 should strictly be (Array2D.base2 data) for non-zero array base

    Also, a slight correction of the first cut, to allow for the general case

    let row = seq { for i in 0..((Array2D.length2 data)-1) ->  data.[rowIndex, i + (Array2D.base2 data)] } |> Seq.toArray




    • Edited by Mr. Tines Saturday, September 1, 2012 9:06 PM Simpler form found
    • Marked as answer by Rainmater Sunday, September 2, 2012 8:10 AM
    Saturday, September 1, 2012 9:03 PM

All replies

  • I'm sure there has to be a simpler way that this, but

    let data = Array2D.create 5 8 0
    let rowIndex = 3 // or whatever
    let row = seq { for i in 0..((Array2D.length2 data)-1) ->  data.[rowIndex,i] } |> Seq.toArray
    does it by the obvious brute-force method.

    • Marked as answer by Rainmater Sunday, September 2, 2012 8:10 AM
    Saturday, September 1, 2012 9:13 AM
  • thank you,

    there aren't any method or function in F# library to do this directly?

    Saturday, September 1, 2012 10:44 AM
  • All the range operations on 2D arrays yield 2D arrays

    > data.[rowIndex..rowIndex, 0..];;
    val it : int [,] = [[0; 0; 0; 0; 0; 0; 0; 0]]

    so at some point you have to do some sequence operation to extract the elements, so you might as well do it straight off.  This is the simplest I've found

    data.[rowIndex..rowIndex, 0..] |> Seq.cast<int> |> Seq.toArray;;
    where 0 should strictly be (Array2D.base2 data) for non-zero array base

    Also, a slight correction of the first cut, to allow for the general case

    let row = seq { for i in 0..((Array2D.length2 data)-1) ->  data.[rowIndex, i + (Array2D.base2 data)] } |> Seq.toArray




    • Edited by Mr. Tines Saturday, September 1, 2012 9:06 PM Simpler form found
    • Marked as answer by Rainmater Sunday, September 2, 2012 8:10 AM
    Saturday, September 1, 2012 9:03 PM