Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# how to append/join array2D and combine 1D arrays to array2D

Tags:

f#

in F#, array.append can join two arrays; is there a way to append 2 array2D objects into one or column-wise join several 1-D arrays into one array2D object?

like image 934
ahala Avatar asked Mar 02 '10 23:03

ahala


2 Answers

The array2D function will turn any seq<#seq<'T>> into a 'T [,] so it should work for turning a bunch of 1D arrays into a 2D array.

let arr1 = [| 1; 2; 3 |]
let arr2 = [| 4; 5; 6 |]

let combined = array2D [| arr1; arr2 |]
like image 52
Joel Mueller Avatar answered Nov 15 '22 10:11

Joel Mueller


As far as I can see, there is no F# library function that would turn several 1D arrays into a single 2D array, but you can write your own function using Array2D.init:

let joinInto2D (arrays:_[][]) = 
  Array2D.init arrays.Length (arrays.[0].Length) (fun i j ->
    arrays.[i].[j])

It takes an array of arrays, so when you call it, you'll give it an array containing all the arrays you want to join (e.g. [| arr1; arr2 |] to join two arrays). The function concatenates multiple 1D arrays into a single 2D array that contains one row for each input array. It assumes that the length of all the given arrays is the same (it may be a good idea to add a check to verify that, for example using Array.forall). The init function creates an array of the specified dimensions and then calls our lambda function to calculate a value for each element - in the lambda function, we use the row as an index in the array of arrays and the column as an index into the individual array.

Here is an example showing how to use the function:

> let arr1 = [| 1; 2; 3 |]
  let arr2 = [| 4; 5; 6 |];;

> joinInto2D [| arr1; arr2 |];;
val it : int [,] = [[1; 2; 3]
                    [4; 5; 6]]

EDIT: There is already a function to do that - nice! I'll leave the answer here, because it may still be useful, for example if you wanted to join 1D arrays as columns (instead of rows, which is the behavior implemented by array2D.

like image 25
Tomas Petricek Avatar answered Nov 15 '22 10:11

Tomas Petricek