6

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?

3 Answers 3

6

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 |]
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

I don't think there's anything built-in to handle this. You can define your own reusable method based on either Array2D.init or Array2D.blit, though. If you need to combine several columns into one logical whole, I think it would frequently be more convenient to use an array of arrays rather than a 2D array (and in general, the 1D array operations in .NET are significantly faster than the multi-dimensional array operations).

1 Comment

thanks. this is very helpful. I had thought array of array is the same as array2D in F#.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.