2013-02-14 48 views
5

我想將製表符分隔的文本文件讀入Breeze DenseMatrix。我在ScalaDoc中看到這應該是可能的,並且有一整套I/O類,但我找不到任何示例,並且很難消化ScalaDoc。從Scala Breeze中的文件中讀取矩陣

有人可以提供一個簡單的讀/寫示例嗎?

回答

3

您可以使用scala.io.Source從文件中讀取製表符分隔的數據。

一些樣本數據:

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

其中DenseMatrix構造函數具有這種形式new DenseMatrix(rows: Int, data: Array[V], offset: Int = 0),所以我會使用它。

獲取的行數:

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

然後獲取數據爲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) 

然後res0res1可以用來創建一個新的DenseMatrix

+2

感謝,雖然在RES1讀時,它是按行優先順序和構造函數預計列重大。所以我使用的構造函數是'DenseMatrix(res1.size/res0).t' – 2013-02-15 13:25:49

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

+0

scala是一個區分大小寫的語言,「文件」應該是「File」。 「val matrix = csvread(new File(」your file localtion「),'$ seperator')」 – 2018-02-23 05:33:20