Exporting matrix values to a file
In data analysis and machine learning, matrices are a popular data structure that often need to be exported and imported into the program. In this recipe, we will export a sample matrix using the Repa I/O library.
Getting ready
Install the repa-io
library using cabal as follows:
$ cabal install repa-io
How to do it…
Create a new file, which we name Main.hs
, and insert the code explained in the following steps:
- Import the relevant libraries as follows:
import Data.Array.Repa.IO.Matrix import Data.Array.Repa
- Define a 4 x 3 matrix as follows:
x :: Array U DIM2 Int x = fromListUnboxed (Z :. (4::Int) :. (3::Int)) [ 1, 2, 9, 10 , 4, 3, 8, 11 , 5, 6, 7, 12 ]
- Write the matrix to a file as follows:
main = writeMatrixToTextFile "output.dat" x
How it works…
The matrix is represented simply as a list of its elements in row-major order. The first two lines of the file define the type of data and the dimensions.
There's more…
To read a matrix...