Read matrix from file in Scala Breeze

I want to read a tab delimited text file in Breeze DenseMatrix. I see in ScalaDoc that this should be possible, and there is a whole set of I / O classes, but I cannot find examples and it is hard to digest ScalaDoc.

Can someone provide a simple read / write example?

+5
source share
2 answers

You can use scala.io.Sourceto read tab delimited data from a file.

Some sample data:

0       1       2       3       4       5
6       7       8       9       10      11

One of the constructors DenseMatrixhas this form new DenseMatrix(rows: Int, data: Array[V], offset: Int = 0), so I will use this.

Get the number of rows:

scala> scala.io.Source.fromFile("TabDelimited.txt").getLines.size
res 0:Int = 2

Then get the data as Array[Int]:

scala> scala.io.Source.fromFile("TabDelimited.txt").getLines.toArray.flatMap(_.split("\t")).map(_.toInt)
res1: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

res0 res1 DenseMatrix.

+3

csv densematrix

import breeze.linalg._
import java.io._
val matrix=csvread(new file("your file localtion"),'$seperator')

api: http://www.scalanlp.org/api/breeze/index.html#breeze.linalg.package

+3

All Articles