I have a txt file with several integer matrices with different dimensions that I want to parse into an hmatrix package representation, but I can't find any suitable functions. The text file contains the following form:
[single-value]
[single-row 1x10 matrix]
[16x16 square-matrix]
repeats unknowingly often
e.g.
9
1 2 3 ..
9 8 7 6 5 ...
.
.
4 3 2 1 0 ..
...
The closest thing I found was readMatrix
at:
but since there is no documentation and I'm fairly new to Haskell I have no idea how to use it.
As long as performance isn't crucial, it's easiest to first preprocess the data as simple lists before introducing any special types like matrices. (And if performance does matter, you shouldn't be using text files!)
So first
readAllNumbers :: String -> [[Double]]
readAllNumbers = map (map read . words) . lines
Then you seperate the structure. In this case, you simply take the first two elements of the list of lines specially, then chunk up the remaining lines à 16. Well, that's about it, you can then simply cast the [nested] Double
lists to matrices:
parseMContents :: String -> (Double, (HMat.Matrix, [HMat.Matrix]))
parseMContents s = case readAllNumbers s of
[singleValue] : singleRow : rest
-> (singleValue, ( HMat.fromLists [singleRow]
, HMat.fromLists <$> chunksÀ 16 rest ) )
_ -> error "Matrix file has wrong format!"
chunksÀ :: Int -> [a] -> [[a]]
chunksÀ n ls = case splitAt n ls of
(hs:[]) -> [hs]
(hs:ts) -> hs : chunksÀ n ts